std::is_heap( ) in C++ with Examples
Last Updated :
21 May, 2020
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:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > arr = { 3, 1, 5, 1, 9, 8 };
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:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > arr = { 3, 1, 5, 1, 9, 8 };
bool isHeap = is_heap(arr.begin(),
arr.end());
if (!isHeap) {
make_heap(arr.begin(), arr.end());
}
else {
cout << "Already Max Heap\n" ;
}
for ( auto & it : arr) {
cout << it << ' ' ;
}
return 0;
}
|
Reference: http://www.cplusplus.com/reference/algorithm/is_heap/
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...