C++ Standard Library C++ STL Library

C++ <algorithm> - make_heap() Function



The C++ algorithm::make_heap function is used to rearrange the elements in the range [first,last) in such a way that they form a max heap.

Syntax

//default version
template <class RandomAccessIterator>
  void make_heap(
     RandomAccessIterator first, 
     RandomAccessIterator last
  );

//custom version 
template <class RandomAccessIterator, class Compare>
  void make_heap(
     RandomAccessIterator first, 
     RandomAccessIterator last,
     BinaryPredicate comp
  );

Parameters

first Specify initial position of the random-access iterator. The range used is [first,last).
last Specify final position of the random-access iterator. The range used is [first,last).
comp A binary predicate that takes two elements in the range as arguments and returns a bool. It follows the strict weak ordering to order the elements.

Return Value

None.

Time Complexity

Up to linear in three times the distance between first and last i.e, Θ(3n), where n is the distance between first and last.

Example:

In the example below, the algorithm::make_heap function is used to rearrange the elements of a given vector to form a max heap.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
int main (){
  vector<int> vec{10, 5, 55, 22, 27, -10};
  vector<int>::iterator it;

  cout<<"vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  //make the vector max heap
  make_heap(vec.begin(), vec.end());

  cout<<"\nAfter make_heap call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

vec contains: 10 5 55 22 27 -10
After make_heap call, vec contains: 55 27 10 22 5 -10

❮ C++ <algorithm> Library