In C++ STL, there is priority_queue that can directly be used to implement Max Heap. 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;
Below is an example for integers.
1 5 10 20 30
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
- Implement your own itoa()
- Implement Your Own sizeof
- K’th Least Element in a Min-Heap
- Using class to implement Vector Quantities in C++
- Implement your own tail (Read last n lines of a huge file)
- Heap in C++ STL | make_heap(), push_heap(), pop_heap(), sort_heap(), is_heap, is_heap_until()
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Heap overflow and Stack overflow
- How to create an unordered_map of pairs in C++?
- Full screen OpenCV / GtK application in C++ running on Raspberry PI
- C++, OpenCV and Gtk3 Windows dev environment
- How to create an unordered_map of user defined class in C++?
- Sum of Bitwise-OR of all subarrays of a given Array | Set 2
- How to delete last element from a set in C++