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:
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.
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:
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.
(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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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)
- How to implement user defined Shared Pointers in C++
- How to implement our own Vector Class in C++?
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- 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