Heap in STL C++

About Heap in STL :

Heap in STL is defined as the container used to store the elements in the order such that the maximum elements always remains on the top.

heap in stl

Working of Heap :

In STL, A heap is a type of data structure that makes access to the topmost (or lowest) member possible in O(1) time. The order of each additional component is dependent on how it is implemented, but it stays constant throughout.The header “algorithm” has a definition of this function.

Functions in Map :

 FunctionWorking
make_heap()convert container in to heap
front()return the front element of the heap.
push_heap()insert element into the heap.
sort_heap()sort the elements of the heap.
pop_heap()

remove the element from the heap.

Example of Heap in STL :

Run
#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
    
    vector vect = {2,3,1,30,20,50,5,10};
    // converting vect to heap
    make_heap(vect.begin(), vect.end());
    cout<<"The elements in the heap :";
    for(auto it : vect){
        cout<< it<<" ";
    }
    cout<< endl;
    cout<< "The maximum element in the heap : "<< vect.front();

    return 0;
}

Output :

The elements in the heap :50 30 5 10 20 1 2 3 
The maximum element in the heap : 50

In the above program, we take the vector with elements and by using make_heap function , convert them in to heap and print the elements of heap.

Example of Heap in STL:

Run
#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
    
    vector vect = {2,3,1,30,20,50,5,10};
    // converting vect to heap
    make_heap(vect.begin(), vect.end());
    cout<<"The elements in the heap :";
    for(auto it : vect){
        cout<< it<<" ";
    }
    
    vect.push_back(100);
    push_heap(vect.begin(), vect.end());
    cout<< endl;
    cout<<"The maximum element in the heap : "<< vect.front();
    cout<< endl;
    sort_heap(vect.begin(), vect.end());
    cout<<"The elements of the heap after sorting : ";
    for(auto it : vect){
        cout<< it<< " ";
    }

    return 0;
}

Output :

The elements in the heap :50 30 5 10 20 1 2 3 
The maximum element in the heap : 100
The elements of the heap after sorting : 1 2 3 5 10 20 30 50 100 

In the above program, we take the vector with elements and by using make_heap function , convert them in to heap and use different function like push_heap, sort_heap to see different result.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription