push_heap

Syntax:

    #include <algorithm>
    void push_heap( random_access_iterator start, random_access_iterator end );
    void push_heap( random_access_iterator start, random_access_iterator end, StrictWeakOrdering cmp );

The push_heap() function adds an element (defined as the last element before end) to a heap (defined as the range of elements between [start,''end-1).

If the strict weak ordering comparison function object cmp is given, then it is used instead of the < operator to compare elements.

push_heap() runs in logarithmic time.

Example

// range heap example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
int main () {
  int myints[] = {10,20,30,5,15};
  vector<int> v(myints,myints+5);
  vector<int>::iterator it;
 
  make_heap (v.begin(),v.end());
  cout << "initial max heap   : " << v.front() << endl;
 
  pop_heap (v.begin(),v.end()); v.pop_back();
  cout << "max heap after pop : " << v.front() << endl;
 
  v.push_back(99); push_heap (v.begin(),v.end());
  cout << "max heap after push: " << v.front() << endl;
 
  sort_heap (v.begin(),v.end());
 
  cout << "final sorted range :";
  for (unsigned i=0; i<v.size(); i++) cout << " " << v[i];
 
  cout << endl;
 
  return 0;
}

Output: initial max heap : 30

max heap after pop : 20

max heap after push: 99

final sorted range : 5 10 15 20 99

Related Topics: is_heap, make_heap, pop_heap, sort_heap