I'm very new to C++, and I was wondering if there was a way to make a min heap in C++ from the standard library.
To build a min heap we:Create a new child node at the end of the heap (last level). Add the new key to that node (append it to the array). Move the child up until you reach the root node and the heap property is satisfied.
First, always insert at the bottom of the tree. The initial position of the inserted element is at the last level. We will now need to update the position of this element so that the min-heap property is satisfied. Since the root node of every sub-tree must be the minimum, check the sub-tree of its immediate parent.
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).
Use make_heap()
and friends, defined in <algorithm>
, or use priority_queue
, defined in <queue>
. The priority_queue
uses make_heap
and friends underneath.
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With