In: Computer Science
How to write a max-heap implementation of a templated priority queue class using the STL std::vector class to hold the data array
C++ program to implement max heap implementation of priority queue using stl std::vectors
#include<bits/stdc++.h>
#include<vector>
using namespace std;
void Push(vector<int>& heap, int value)
{
heap.push_back(value);
push_heap(heap.begin(), heap.end(), greater<int>());
}
int Pop(vector<int>& heap)
{
int value1 = heap.front();
// Now, This operation will transfer the smallest element to the very end of the vector
pop_heap(heap.begin(), heap.end(), greater<int>());
//Now, Removes the last element from the vector, which is also the smallest element
heap.pop_back();
return value1;
}
// Main function
int main()
{
vector<int> heap1;
Push(heap1, 1);
Push(heap1, 7);
Push(heap1, 5);
while (!heap1.empty())
{
cout << Pop(heap1) << "\n";
}
return 0;
}
Output screen:
Thank you!!! Good luck! keep coding :)