Javatpoint Logo
Javatpoint Logo

C++ Algorithm pop_heap()

C++ Algorithm pop_heap() function is used to swap the value in the position ?first? and the value in the position ?last-1? and makes the sub range [first, last-1) into a max heap. It has the effect of removing the first (largest) element from the heap defined by the range [first, last).

Elements are compared using operator < for the first version or using the given binary comparison function comp for the second version.

Note: A max heap is a range of elements [first, last) that has the following properties:

  • N = last - first, for all 0 < i < N, f [floor (i-1, 2)] does not compare less than f[i].
  • a new element can be added using std::push_heap()
  • the first element can be removed using std::pop_heap()

Syntax

Parameter

first: A random access iterator pointing to the first element in the heap.

last: A random access iterator pointing to the past last element in the heap.

comp: A user-defined binary predicate function that accepts two arguments and returns true if the two arguments are in order otherwise, it returns false. It follows the strict weak ordering to order the elements.

Return value

None

Complexity

Complexity is up to twice logarithmic in the distance between first and last: compares elements and potentially swaps (or moves) them until rearranges as a longer heap.

Data races

Some of the objects in the range [first, last) are modified.

Exceptions

This function throws an exception if any of element comparison, the element swapping, or an operation on iterator throws an exception.

Note: The invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of pop_heap():

Output:

v2 after 152 popped from heap

v2 after 98 popped from heap

v2 after 77 popped from heap

v2 after 40 popped from heap

v2 after 31 popped from heap

v2 after 22 popped from heap

v2 after 13 popped from heap

v2 after 13 popped from heap

v2 after 10 popped from heap

v2 after 1 popped from heap

Example 2

Let's see another simple example:

Output:

v: 9 5 4 1 1 3 
after pop_heap: 5 3 4 1 1 9 
largest element: 9
heap without largest: 5 3 4 1 1

Example 3

Let's see another simple example:

Output:

on entry:           3 4 5 6 7 5 6 7 8 9 1 2 3 4 
after make_heap():  9 8 6 7 7 5 5 3 6 4 1 2 3 4 
after pop_heap():   8 7 6 7 4 5 5 3 6 4 1 2 3 

Example 4

Let's see a simple example:

Output:

The heaped version of vector v1 is ( 9 7 8 5 1 6 3 2 4 ).
The reheaped v1 with 10 added is ( 10 9 8 5 7 6 3 2 4 1 ).
The heap v1 with 10 removed is ( 9 7 8 5 1 6 3 2 4 10 ).

The 'greater than' reheaped v1 puts the smallest element first:
 ( 0 1 3 4 2 6 8 5 9 10 7 ).
The 'greater than' heaped v1 with the smallest element
 removed from the heap is: ( 1 2 3 4 7 6 8 5 9 10 0 ).

Next TopicC++ Algorithm




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA