std::is_heap( ) in C++ with Examples
The std::is_heap() function in C++ Standard Template Library is used to check whether a given range of elements forms Max Heap or not. It returns True when given ranges of elements forms Max Heap, else it returns False.
Header File:
#include <algorithm>
Syntax:
is_heap(first, last)
Parameter: It takes two parameters, iterators pointing towards the first and last element of the range.
Return Value: The function returns the following value:
- True: If the elements in the range [first, last) forms a Max Heap.
- False: If the elements in the range [first, last) doesn’t forms a Max Heap.
Below is the program to illustrate std::is_heap():
Program 1:
// C++ program to illustrate // the std::is_heap() #include <algorithm> #include <iostream> #include <vector> using namespace std; // Driver Code int main() { // Given list of numbers vector< int > arr = { 3, 1, 5, 1, 9, 8 }; // Check if arr[] forms max-heap or not bool isHeap = is_heap(arr.begin(), arr.end()); if (isHeap) { cout << "Forms a Max Heap" ; } else { cout << "Doesn't forms a Max Heap" ; } } |
Output:
Doesn't forms a Max Heap
Program 2:
// C++ program to illustrate the std::is_heap() #include <algorithm> #include <iostream> #include <vector> using namespace std; // Driver Code int main() { // Given list of numbers vector< int > arr = { 3, 1, 5, 1, 9, 8 }; // Check if arr[] forms max-heap or not bool isHeap = is_heap(arr.begin(), arr.end()); // isHeap is false then make Max Heap // using in built function make_heap if (!isHeap) { make_heap(arr.begin(), arr.end()); } // Else already a heap else { cout << "Already Max Heap\n" ; } // Print all the elements of arr // after make Max Heap for ( auto & it : arr) { cout << it << ' ' ; } return 0; } |
Output:
9 3 8 1 1 5
Reference: http://www.cplusplus.com/reference/algorithm/is_heap/
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.