std::is_heap_until() 算法
- 自 C++20 起
- 自 C++17 起
- 自 C++11 起
// (1)
template< class RandomIt >
constexpr RandomIt is_heap_until( RandomIt first, RandomIt last );
// (2)
template< class RandomIt, class Compare >
constexpr RandomIt is_heap_until( RandomIt first, RandomIt last, Compare comp );
// (3)
template< class ExecutionPolicy, class RandomIt >
RandomIt is_heap_until( ExecutionPolicy&& policy, RandomIt first, RandomIt last );
// (4)
template< class ExecutionPolicy, class RandomIt, class Compare >
RandomIt is_heap_until( ExecutionPolicy&& policy, RandomIt first, RandomIt last, Compare comp );
// (1)
template< class RandomIt >
RandomIt is_heap_until( RandomIt first, RandomIt last );
// (2)
template< class RandomIt, class Compare >
RandomIt is_heap_until( RandomIt first, RandomIt last, Compare comp );
// (3)
template< class ExecutionPolicy, class RandomIt >
RandomIt is_heap_until( ExecutionPolicy&& policy, RandomIt first, RandomIt last );
// (4)
template< class ExecutionPolicy, class RandomIt, class Compare >
RandomIt is_heap_until( ExecutionPolicy&& policy, RandomIt first, RandomIt last, Compare comp );
// (1)
template< class RandomIt >
RandomIt is_heap_until( RandomIt first, RandomIt last );
// (2)
template< class RandomIt, class Compare >
RandomIt is_heap_until( RandomIt first, RandomIt last, Compare comp );
检查范围 [first
; last
),并找到以 first
开头的最大范围,该范围是一个最大堆。
-
(1) 元素使用
operator<
进行比较。 -
(2) 元素使用给定的二元比较函数
comp
进行比较。 -
(3 - 4) 与 (1 - 2) 相同,但根据
policy
执行。重载决议这些重载只有在
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
(C++20 之前)std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>
(C++20 起) 为true
时才参与重载决议。
参数
first last | 要检查的元素范围。 |
policy | 要使用的执行策略。有关详细信息,请参阅执行策略。 |
comp | 比较函数对象(即满足 Compare 要求的对象)。比较函数的签名应等同于以下内容:
|
类型要求
RandomIt | LegacyRandomAccessIterator |
返回值
以 first
开头的最大堆的最大范围的上限。
也就是说,范围 [first
; it
) 是最大堆的最后一个迭代器 it
。
复杂度
与 first
和 last
之间的距离成线性关系。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数执行抛出异常,并且
ExecutionPolicy
是标准策略之一,则调用std::terminate
。对于任何其他ExecutionPolicy
,行为是实现定义的. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
备注
最大堆是具有以下属性的元素范围 [f
; l
)
- 给定
N
为l - f
,对于所有0 < i < N
,f[(i - 1) / 2]
不与f[i]
比较小。 - 可以使用
std::push_heap
在 O(log(N)) 时间内添加新元素。 - 可以使用
std::pop_heap
在 O(log(N)) 时间内移除第一个元素。
示例
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v {3, 1, 4, 1, 5, 9};
std::make_heap(v.begin(), v.end());
// probably mess up the heap
v.push_back(2);
v.push_back(6);
auto heap_end = std::is_heap_until(v.begin(), v.end());
std::cout << "all of v: ";
for (auto i : v) std::cout << i << ' ';
std::cout << '\n';
std::cout << "only heap: ";
for (auto i = v.begin(); i != heap_end; ++i) std::cout << *i << ' ';
std::cout << '\n';
}
all of v: 9 5 4 1 1 3 2 6
only heap: 9 5 4 1 1 3 2