How to implement max-heap using C++ STL?

A max-heap is a binary tree such that:
1. The data contained in each node is greater than (or equal to) the data in that node’s children.
2. The binary tree is complete

The C++ Standard Library consists of a container named priority_queue. A priority queue is a max-heap.

Example of a heap using priority queue:

#include <queue>
#include <iostream>

using namespace std;

int main()
{
    priority_queue<int> maxHeap;
    maxHeap.push(3); //inserting elements into heap
    maxHeap.push(5);
    maxHeap.push(1);
    maxHeap.push(-12);

    while (!maxHeap.empty())
    {
        cout<<maxHeap.top()<<" ";
        maxHeap.pop();  //removing elements from a heap
    }

    return 0;
}

Output:

5  3  1  -12

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top