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:
CPP
// C++ program to show that priority_queue is by// default a Max Heap#include <bits/stdc++.h>using namespace std;// Driver codeint 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;} |
30 20 10 5 1
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 factor (aka function object) that must have bool as return-type and must have 2 arguments.
Below is an example for integers.
CPP
// C++ program to use priority_queue to implement min heap#include <bits/stdc++.h>using namespace std;// Driver codeint 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;} |
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++
// C++ Progrma to implement min heap// using default priority_queue(max-heap)#include <iostream>#include <queue>using namespace std;int main(){ // data int arr[] = { 25, 7, 9, 15, 20, 36, 50 }; // default priority_queue using max-heap priority_queue<int> pq; // size of the array int n = sizeof(arr) / sizeof(arr[0]); // multiply -1 with all elements while // inserting for (int i = 0; i < n; i++) { pq.push((-1) * arr[i]); } // multiply all elements with -1 while // retrive the elements while (!pq.empty()) { cout << (pq.top()) * (-1) << " "; pq.pop(); } return 0;} |
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.
CPP
// C++ program to use priority_queue to implement Min Heap// for user defined class#include <bits/stdc++.h>using namespace std;// User defined class, Pointclass Point{ int x; int y;public: Point(int _x, int _y) { x = _x; y = _y; } int getX() const { return x; } int getY() const { return y; }};// To compare two pointsclass myComparator{public: int operator() (const Point& p1, const Point& p2) { return p1.getX() > p2.getX(); }};// Driver codeint main (){ // Creates a Min heap of points (order by x coordinate) priority_queue <Point, vector<Point>, myComparator > pq; // Insert points into the min heap pq.push(Point(10, 2)); pq.push(Point(2, 1)); pq.push(Point(1, 5)); // One by one extract items from min heap 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)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
Recommended Posts:
- K’th Least Element in a Min-Heap
- Heap in C++ STL | make_heap(), push_heap(), pop_heap(), sort_heap(), is_heap, is_heap_until()
- Program to implement Separate Chaining in C++ STL without the use of pointers
- Priority Queue using Binary Heap
- Using class to implement Vector Quantities in C++
- Heap overflow and Stack overflow
- Implement Your Own sizeof
- Implement your own itoa()
- Implement your own tail (Read last n lines of a huge file)
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- How to implement user defined Shared Pointers in C++
- How to implement our own Vector Class in C++?
- Count number of unique Triangles using STL | Set 1 (Using set)
- std::min in C++
- valarray min() in C++
- std::uniform_int_distribution min() method in C++ with examples
- std::uniform_real_distribution min() method in C++ with Examples
- Kruskal's Minimum Spanning Tree using STL in C++
- Dijkstra’s shortest path algorithm using set in STL
- Dijkstra's Shortest Path Algorithm using priority_queue of STL

