template<class RandomIt>
RandomIt is_heap_until(RandomIt first, RandomIt last);
template<class RandomIt, class Compare>
RandomIt is_heap_until(RandomIt first, RandomIt last, Compare comp);
Parameters
Parameter
Description
first, last
Required. The range to check.
comp
Optional. The comparison used for the heap.
Return Value
Return Value
Description
Iterator
Points at the first element that breaks the heap order.
last
Returned when the whole range is a heap.
C++ Examples
Example 1 — Find the break
A new value was added without push_heap.
C++
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {9, 5, 4, 1, 3, 7};
auto it = std::is_heap_until(v.begin(), v.end());
std::cout << "Heap part length: " << (it - v.begin()) << '\n';
return 0;
}
Output
Heap part length: 5
How It Works
The first five values 9, 5, 4, 1 and 3 follow the heap rule.
The last value, 7, sits under 4, but 7 is bigger than 4.
So the rule breaks at index 5.
Example 2 — Whole range is a heap
A heap returns the end iterator.
C++
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {10, 6, 8};
auto it = std::is_heap_until(v.begin(), v.end());
if (it == v.end()) {
std::cout << "Whole range is a heap\n";
}
return 0;
}
Output
Whole range is a heap
How It Works
10 is bigger than both 6 and 8.
No element breaks the rule.
The function returns v.end().
Example 3 — Min-heap break
Use std::greater to look for a min-heap.
C++
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 3, 2, 0};
auto it = std::is_heap_until(v.begin(), v.end(), std::greater<int>());
std::cout << "Min-heap part length: " << (it - v.begin()) << '\n';
return 0;
}
Output
Min-heap part length: 3
How It Works
In a min-heap, a child must not be smaller than its parent.
1, 3 and 2 are fine, but the last value 0 is smaller than its parent 3.
The break is at index 3.
Frequently Asked Questions
In C++, std::is_heap_until() finds the first element that breaks the heap rule. Include <algorithm> to use it.
Include <algorithm>. It needs C++11 or newer, so compile with -std=c++11 or later.
It returns an iterator to the first element that breaks the heap rule, or the last iterator if the whole range is a heap.
is_heap() answers true or false. is_heap_until() also tells you where the heap rule breaks.
No. It only reports the position. Call make_heap() to fix the range.