C++ Standard Library sort_heap() Sample

Description

sort_heap() is used in the construction of a heap data structure. A heap is an organization of a sequence, such that the first element is the largest in the sequence, and the first element may be removed, or a new element added to the heap, in O(logN) time.

push_heap(first,last) pushes the value *(last-1), and pop_heap(first,last) removes the first heap element by swapping it with *(last-1) and making (first,last-1) into a heap. The idea here is that a heap can be grown incrementally, an element at a time.

make_heap() turns an unsorted sequence of elements into a heap, and sort_heap() turns a heap into a sorted sequence of elements.

Declaration

	template <class Ran>
	    void sort_heap(Ran, Ran);
	template <class Ran, class Cmp>
	    void sort_heap(Ran, Ran, Cmp);

Concept

The example program uses the heap operations in the library to implement a priority queue data structure, one where the elements are represented in order from highest to lowest. make_heap() is called to create a heap from the unordered vector of integers passed to the constructor. push_heap() is used to implement push(), for any elements that are added to the queue, and pop_heap() is used for the pop() function. Finally, sort_heap() is used to convert the heap back into a sequence of elements. The output of the program is:

	-3
	1
	5
	14
	17
	17
	14
	5
	1
	-3
Converting from a heap into a sequence has the effect of reversing the order.

Supported
Supported
Supported