The C++ Standard Library consists of the header, <algorithm>
which defines a collection of functions (principally designed to deal with a range of elements). make_heap()
is a method in the STL that rearranges the elements in a given range in such a way that they form a heap.
Syntax:
make_heap( iterator_begin, iterator_end, comparator ); //comparator is optional
Parameters: The make_heap()
method accepts 3 parameters
- iterator_begin: Iterator to the initial position of new heap
- iterator_end: Iterator to the final position of new heap ( Note: the range is [iterator_begin,iterator_end) )
- comparator: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.
Return value: none
Example of make_heap() method
#include<iostream> #include<algorithm> #include<vector> using namespace std; void print(vector<int> v) { vector<int>::iterator it; for(it = v.begin(); it !=v.end(); ++it) cout<< *it <<" "; cout<<endl; } int main() { vector<int> v; v.push_back(4); v.push_back(3); v.push_back(8); v.push_back(-5); v.push_back(7); cout<<"Before heap: "<<endl; print(v); make_heap(v.begin(), v.end()); cout<<"After heap: "<<v.front()<<endl; print(v); make_heap(v.begin(), v.end(), greater<int>()); //creates a min heap cout<<"After heap: "<<v.front()<<endl; print(v); }
Output:
Before heap: 4 3 8 -5 7 After heap: 8 7 4 -5 3 After heap: -5 3 4 7 8