Skip to content

Instantly share code, notes, and snippets.

@naveenspace7
Created June 26, 2020 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naveenspace7/f3395243e7b720720e01dd90dca16e03 to your computer and use it in GitHub Desktop.
Save naveenspace7/f3395243e7b720720e01dd90dca16e03 to your computer and use it in GitHub Desktop.
This is a small demo showing the usage of priority queues and standalone heap
#include <iostream>
#include <queue>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
class Compare {
public:
bool operator()(const int& v1, const int& v2)
{
return v1 > v2; // min heap
}
};
// standalone min heap
void vector_min_heap(vector<int> v)
{
make_heap(begin(v), end(v), [](const int& i1, const int& i2) {return i1 > i2;}); // rearrange the elements to form a heap
v.push_back(21); push_heap(begin(v), end(v), [](const int& i1, const int& i2) {return i1 > i2;});
for_each(begin(v), end(v), [](const int& i) { cout << i << ' '; });
cout << endl;
}
// standalone max heap
void vector_max_heap(vector<int> v)
{
// make_heap(begin(v), end(v)); // same as below
make_heap(begin(v), end(v), [](const int& i1, const int& i2) {return i1 < i2;}); // rearrange the elements to form a heap
// v.push_back(21); push_heap(begin(v), end(v)); // same as below
v.push_back(21); push_heap(begin(v), end(v), [](const int& i1, const int& i2) {return i1 < i2;});
for_each(begin(v), end(v), [](const int& i) { cout << i << ' '; });
cout << endl;
}
int main()
{
int data[] = {23,56,78,77,21};
priority_queue<int, vector<int>, greater<int>> pq_min_heap (begin(data), end(data)); // also makes a heap
priority_queue<int, vector<int>, less<int>> pq_max_heap (begin(data), end(data)); // also makes a heap
priority_queue<int> pq_default (begin(data), end(data)); // also makes a heap
priority_queue<int, vector<int>, Compare> pq_func_obj (begin(data), end(data)); // also makes a heap
pq_min_heap.push(7);
pq_min_heap.push(100);
cout << "Expecting top(pq_min_heap) 7: " << pq_min_heap.top() << endl;
pq_min_heap.pop();
cout << "Expecting top(pop(pq_min_heap)) 21: " << pq_min_heap.top() << endl;
vector<int> v {1,7,4,8,10,17,8};
vector_min_heap(v);
vector_max_heap(v);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment