How to implement Min Heap using STL?
Last Updated :
10 Jan, 2023
In C++ STL, there is priority_queue that can directly be used to implement Max Heap. In order to fully understand the code, make sure you are familiar with following concepts in C++
See below example:
C++
#include <bits/stdc++.h>
using namespace std;
int main ()
{
priority_queue < int > pq;
pq.push(5);
pq.push(1);
pq.push(10);
pq.push(30);
pq.push(20);
while (pq.empty() == false )
{
cout << pq.top() << " " ;
pq.pop();
}
return 0;
}
|
Since elements are printed in descending order, we have a max heap by default.
How to implement Min Heap?
priority_queue supports a constructor that requires two extra arguments to make it min-heap.
priority_queue <Type, vector<Type>, ComparisonType > min_heap;
`The third parameter, ‘Comparison Type’ can either be a function or functor (aka function object) that must have bool as return-type and must have 2 arguments.
Below is an example for integers.
C++
#include <bits/stdc++.h>
using namespace std;
int main ()
{
priority_queue < int , vector< int >, greater< int > > pq;
pq.push(5);
pq.push(1);
pq.push(10);
pq.push(30);
pq.push(20);
while (pq.empty() == false )
{
cout << pq.top() << " " ;
pq.pop();
}
return 0;
}
|
Output:
1 5 10 20 30
Another method for making min-heap using default priority_queue:
This is frequently used in Competitive Programming. We first multiply all elements with (-1). Then we create a max heap (max heap is the default for priority queue). When we access the data and want to print it we simply multiply those elements with (-1) again.
Below is the implementation of the above idea:
C++
#include <iostream>
#include <queue>
using namespace std;
int main()
{
int arr[] = { 25, 7, 9, 15, 20, 36, 50 };
priority_queue< int > pq;
int n = sizeof (arr) / sizeof (arr[0]);
for ( int i = 0; i < n; i++) {
pq.push((-1) * arr[i]);
}
while (!pq.empty()) {
cout << (pq.top()) * (-1) << " " ;
pq.pop();
}
return 0;
}
|
Output
7 9 15 20 25 36 50
How to make a min-heap of user-defined class?
Let us consider below example where we build a min-heap of 2 D points ordered by X-axis.
C++
#include <bits/stdc++.h>
using namespace std;
class Point
{
int x;
int y;
public :
Point( int x, int y)
{
this ->x = x;
this ->y = y;
}
int getX() const { return x; }
int getY() const { return y; }
};
class myComparator
{
public :
int operator() ( const Point& p1, const Point& p2)
{
return p1.getX() > p2.getX();
}
};
int main ()
{
priority_queue <Point, vector<Point>, myComparator > pq;
pq.push(Point(10, 2));
pq.push(Point(2, 1));
pq.push(Point(1, 5));
while (pq.empty() == false )
{
Point p = pq.top();
cout << "(" << p.getX() << ", " << p.getY() << ")" ;
cout << endl;
pq.pop();
}
return 0;
}
|
Output:
(1, 5)
(2, 1)
(10, 2)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...