C++ Standard Library C++ STL Library

C++ <algorithm> - push_heap() Function



The C++ algorithm::push_heap function is used to extend the range of max heap by one. Given that the initial range of the heap is [first, last-1), this function extends its range to [first, last) by placing the element at position (last-1) to its corresponding position.

Syntax

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

//custom version 
template <class RandomAccessIterator, class Compare>
  void push_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 logarithmic in the distance between first and last i.e, Θ(log(n)), where n is the distance between first and last.

Example:

In the example below, the algorithm::push_heap function is used to extend the max heap range by one and rearrange the subrange into 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;

  //add a new element at the end of the vector
  vec.push_back(50);

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

  //calling push_heap function which extends
  //the max heap range by 1 and rearranges
  //the subrange into max heap
  push_heap(vec.begin(), vec.end());

  cout<<"\nAfter push_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
After adding new element, vec contains: 55 27 10 22 5 -10 50
After push_heap call, vec contains: 55 27 50 22 5 -10 10

❮ C++ <algorithm> Library