Priority queue in C++ and python
2 min readJan 22, 2020
By default, python support min priority queue while C++ supports max priority queue.
C++
Min and Max priority queue implementations in C++
https://stackoverflow.com/questions/2786398/is-there-an-easy-way-to-make-a-min-heap-in-c
#include <queue> // functional,iostream,ctime,cstdlib
using namespace std;
int main(int argc, char* argv[])
{
srand(time(0));
priority_queue<int,vector<int>,greater<int> > q;
for( int i = 0; i != 10; ++i ) q.push(rand()%10);
cout << "Min-heap, popped one by one: ";
while( ! q.empty() ) {
cout << q.top() << ' '; // 0 3 3 3 4 5 5 6 8 9
q.pop();
}
cout << endl;
return 0;
}
Max heap
// C++ program to show that priority_queue is by
// default a Max Heap
#include <bits/stdc++.h>
using namespace std;// Driver code
int main ()
{
// Creates a max heap
priority_queue <int> pq;
pq.push(5);
pq.push(1);
pq.push(10);
pq.push(30);
pq.push(20);// One by one extract items from max heap
while (pq.empty() == false)
{
cout << pq.top() << " ";
pq.pop();
}return 0;
}
Min heap
// C++ program to use priority_queue to implement min heap
#include <bits/stdc++.h>
using namespace std;// Driver code
int main ()
{
// Creates a min heap
priority_queue <int, vector<int>, greater<int> > pq;
pq.push(5);
pq.push(1);
pq.push(10);
pq.push(30);
pq.push(20);// One by one extract items from min heap
while (pq.empty() == false)
{
cout << pq.top() << " ";
pq.pop();
}return 0;
}
Note : The above syntax is difficult to remembers, so in case of numeric values, we can multiply values with -1 and use max heap to get the effect of min heap
Python
python is relatively simple. We can use -item to change min priority queue to max priority queue.
import heapq
#min heap
a = [6,1,0,4,5,6]
heapq.heapify(a)
while a:
print(heapq.heappop(a))
"""
0
1
4
5
6
6
"""
#max heap
a = [6,1,0,4,5,6]
a = [-item for item in a]
heapq.heapify(a)
while a:
print(-heapq.heappop(a))
"""
6
6
5
4
1
0
"""