make_heap() is used to transform a sequence into a heap. A heap is a data structure which points to highest( or lowest) element and making its access in O(1) time. Order of all the other elements depends upon particular implementation, but remains consistent throughout. This function is defined in the header “algorithm“. There are two implementations of make_heap() function. Both of them are explained through this article.
Syntax 1 : make_heap(iter_first, iter_last)
Template : void make_heap (RandomAccessIterator first, RandomAccessIterator last); Parameters : first : The pointer to the starting element of sequence that has to be transformed into heap. last : The pointer to the next address to last element of sequence that has to be transformed into heap.
Below is the demonstrating code :
CPP
#include<iostream>
#include<algorithm> // for heap
#include<vector>
using namespace std;
struct greaters{
bool operator()( const long & a, const long & b) const {
return a>b;
}
};
int main()
{
vector< int > vi = { 15, 6, 7, 9, 11, 45 };
make_heap(vi.begin(),vi.end(), greaters());
cout << "The minimum element of heap is : " ;
cout << vi.front() << endl;
}
|
Output
The maximum element of heap is : 11
Syntax 2 : make_heap(iter_first, iter_last, comp)
Template : void make_heap (RandomAccessIterator first, RandomAccessIterator last, comp); Parameters : first : The pointer to the starting element of sequence that has to be transformed into heap. last : The pointer to the next address to last element of sequence that has to be transformed into heap. comp : The comparator function that returns a boolean true/false of the each elements compared. This function accepts two arguments. This can be function pointer or function object and cannot change values.
Below is the demonstrating code :
CPP
#include<iostream>
#include<algorithm> // for heap
#include<vector>
using namespace std;
int main()
{
vector< int > vi = { 15, 6, 7, 9, 11, 19};
int k = 3;
make_heap(vi.begin(),vi.end());
int a = 10;
for ( int i=0; i<k; i++)
{
vi.push_back(a);
push_heap(vi.begin(), vi.end());
cout << "Job with maximum priority is : " ;
cout << vi.front() << endl;
a = a + 10;
}
}
|
Output
The minimum element of heap is : 6
Possible application : This function can be used in scheduling. In scheduling, a new element is inserted dynamically in iterations. Sorting again and again to get maximum takes much complexity O(nlogn), instead of that we use “push_heap()” function to heapify the heap made in O(logn) time . The code below depicts its implementation.
Implementation:
Output
Job with maximum priority is : 19
Job with maximum priority is : 20
Job with maximum priority is : 30
Last Updated :
18 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...