Javatpoint Logo
Javatpoint Logo

C++ Algorithm make_heap()

C++ Algorithm make_heap() function is used to rearrange the elements in the range [first, last) in such a way that they form a heap.

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

Syntax

Parameter

first: A random access iterator pointing to the first element in the range to be converted into a heap.

last: A random access iterator pointing to the past last element in the range to be converted into a heap.

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

Return value

None

Complexity

Complexity is up to linear in three times 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 comparisons, the element swaps (or moves) 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 make_heap():

Output:

4
3
2
1

Example 2

Let's see another simple example:

Output:

initial max heap   : 30
max heap after pop : 20
max heap after push: 99
final sorted range : 5 10 13 20 99

Example 3

Let's see another simple example to convert an arbitrary vector of integers into a heap using comparison function:

Output:

Here are the values in the vector:
15 27 16 20 30 100 3 16 7 
Now we make these values into a (minimum) heap.
Here are the revised contents of the vector:
3 7 15 16 30 100 16 27 20  

Example 4

Let's see a simple example:

Output:

initially, v: 3 1 4 1 5 9 
after make_heap, v: 9 5 4 1 1 3 
largest element: 9
after removing the largest element, v: 5 3 4 1 1

Next TopicC++ Algorithm





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA