Home » C++ algorithm is_heap() function

C++ algorithm is_heap() function

by Online Tutorials Library

C++ Algorithm is_heap()

C++ Algorithm is_heap() function is used to check whether the elements in the range [first, last) form a heap. It returns true if the elements in the specified range forms 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 of a range to chaeck for a heap.

last: A random access iterator pointing to the past last element in the range to check for 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

It returns true if the elements in the specified range forms a heap otherwise it returns false.

Complexity

Complexity is up to linear in one less than the distance between first and last: compares pairs of elements until a mismatch is found.

Data races

The objects in the range [first, last) are accessed.

Exceptions

This function throws an exception if either an element comparisons 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 is_heap():

Output:

before: is heap? false   after: is heap? true  

Example 2

Let’s see another simple example:

Output:

initially, v: 2 3 4 1 5 9   making heap...  after make_heap, v: 9 5 4 1 3 2   

Example 3

Let’s see another simple example:

Output:

Given sequence is not a max heap.  Given sequence is a max heap.  

Example 4

Let’s see a simple example:

Output:

Popping out elements: 9 8 7 6 5 4 3 2 1  

Next TopicC++ Algorithm

You may also like