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.
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.
#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.
#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
Login/Signup to comment