Question: I asked a question earlier asking for help to create a program that used a heap to create a priority queue and it was answered.
I asked a question earlier asking for help to create a program that used a heap to create a priority queue and it was answered.
Part of the answer though included this...
heap.template
template unsigned int heap::max_child (unsigned int index) const { unsigned int left_child(index*2+1); unsigned int right_child(index*2+2); assert(v.size() > left_child); if (v.size() > right_child) { if (v[left_child] > v[right_child]) { return left_child; } else { return right_child; } } else { return left_child; } }
template heap::heap() : v() { }
template unsigned int heap::size() const { return v.size(); }
template bool heap::is_empty() const { if (size() == 0) { return true; } return false; }
template void heap::insert (const T& item) { v.push_back(item); unsigned int child_index = size()-1; unsigned int parent_index = (child_index-1)/2; if (parent_index < 0) { return; } while (child_index > 0) { if (v[parent_index] < v[child_index]) { T tmp = v[parent_index]; v[parent_index] = v[child_index]; v[child_index] = tmp; child_index = parent_index; parent_index = (child_index-1)/2; } else { break; } } }
template void heap::remove() { assert(!is_empty()); if (size() == 1) { v.erase(v.begin()); return; } v[0] = v[v.size()-1]; v.erase(v.begin()+v.size()-1); unsigned int parent_index = 0; unsigned int child_index = 0; while (size() > parent_index*2+1) { child_index = max_child(parent_index); if (v[child_index] > v[parent_index]) { T tmp = v[parent_index]; v[parent_index] = v[child_index]; v[child_index] = tmp; parent_index = child_index; } else { break; } } }
template T heap::max() const { assert(!is_empty()); return v[0]; }
template T& heap::max() { assert(!is_empty()); return v[0]; }
and im unsure how to implement this code or how to make a template