Silicon Graphics, Inc.

push_heap

Category: algorithms Component type: function

Prototype

Push_heap is an overloaded name; there are actually two push_heap functions.
template <class RandomAccessIterator>
void push_heap(RandomAccessIterator first, RandomAccessIterator last);

template <class RandomAccessIterator, class StrictWeakOrdering>
void push_heap(RandomAccessIterator first, RandomAccessIterator last,
               StrictWeakOrdering comp);

Description

Push_heap adds an element to a heap [1]. It is assumed that [first, last - 1) is already a heap; the element to be added to the heap is *(last - 1).

The two versions of push_heap differ in how they define whether one element is less than another. The first version compares objects using operator<, and the second compares objects using a function object comp. The postcondition for the first version is that is_heap(first, last) is true, and the postcondition for the second version is that is_heap(first, last, comp) is true.

Definition

Declared in algo.h. The implementation is in heap.h.

Requirements on types

For the first version: For the second version:

Preconditions

For the first version: For the second version:

Complexity

Logarithmic. At most log(last - first) comparisons.

Example

int main()
{
  int A[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

  make_heap(A, A + 9);
  cout << "[A, A + 9)  = ";
  copy(A, A + 9, ostream_iterator<int>(cout, " "));
  
  push_heap(A, A + 10);
  cout << endl << "[A, A + 10) = ";
  copy(A, A + 10, ostream_iterator<int>(cout, " "));
  cout << endl;
}

The output is

[A, A + 9)  = 8 7 6 3 4 5 2 1 0 
[A, A + 10) = 9 8 6 3 7 5 2 1 0 4 

Notes

[1] A heap is a particular way of ordering the elements in a range of random access iterators [f, l). The reason heaps are useful (especially for sorting, or as priority queues) is that they satisfy two important properties. First, *f is the largest element in the heap. Second, it is possible to add an element to a heap (using push_heap), or to remove *f, in logarithmic time. Internally, a heap is a tree represented as a sequential range. The tree is constructed so that that each node is less than or equal to its parent node.

See also

make_heap, pop_heap, sort_heap, is_heap, sort
[Silicon Surf] [STL Home]
Copyright © 1996 Silicon Graphics, Inc. All Rights Reserved. TrademarkInformation