std::push_heap
| 定义于头文件 <algorithm>
|
||
template< class RandomIt >
void push_heap( RandomIt first, RandomIt last );
|
(1) | (自C++20起为constexpr) |
template< class RandomIt, class Compare >
void push_heap( RandomIt first, RandomIt last, Compare comp );
|
(2) | (自C++20起为constexpr) |
将位于位置 last - 1 的元素插入到堆 [first, last - 1)中。插入后的堆将是 [first, last)。
operator<(C++20前)std::less{}(自C++20起) 进行比较的。comp 进行比较的。如果满足以下任何条件,则行为未定义:
[first,last - 1)不是相对于相应比较器的堆。
|
(C++11前) |
| (自C++11起) |
参数
| first, last | - | 定义构成插入后二叉堆元素范围的迭代器对 |
| comp | - |
比较函数对象(即满足
比较
要求的对象),当第一个参数
小于
第二个时返回
true
。
比较函数的签名应等价于如下形式: bool cmp ( const Type1 & a, const Type2 & b ) ;
虽然签名不需要包含
const
&
,但函数不得修改传递给它的对象,且必须能够接受所有(可能为 const 的)
|
| 类型要求 | ||
-
RandomIt
必须满足
随机访问迭代器
的要求。
|
||
-
Compare
必须满足
比较
的要求。
|
||
复杂度
给定 N 为 std:: distance ( first, last ) :
示例
#include <algorithm> #include <iostream> #include <string_view> #include <vector> void println(std::string_view rem, const std::vector<int>& v) { std::cout << rem; for (int e : v) std::cout << e << ' '; std::cout << '\n'; } int main() { std::vector<int> v{3, 1, 4, 1, 5, 9}; std::make_heap(v.begin(), v.end()); println("after make_heap: ", v); v.push_back(6); println("after push_back: ", v); std::push_heap(v.begin(), v.end()); println("after push_heap: ", v); }
输出:
after make_heap: 9 5 4 1 1 3 after push_back: 9 5 4 1 1 3 6 after push_heap: 9 5 6 1 1 3 4
缺陷报告
下列行为变更缺陷报告被追溯应用于先前发布的C++标准。
| 缺陷报告 | 应用于 | 发布时行为 | 正确行为 |
|---|---|---|---|
| LWG 3032 | C++98 |
未要求
[
first
,
last
)
范围内的元素可交换
|
要求可交换 |
参见
(C++11) |
检查给定范围是否为最大堆 (函数模板 & 算法函数对象) |
(C++20) |
|
(C++11) |
查找作为最大堆的最大子范围 (函数模板 & 算法函数对象) |
(C++20) |
|
| 从元素范围创建一个最大堆 (函数模板 & 算法函数对象) | |
(C++20) |
|
| 从最大堆移除最大元素 (函数模板 & 算法函数对象) | |
(C++20) |
|
| 将最大堆转换为按升序排序的元素范围 (函数模板 & 算法函数对象) | |
(C++20) |
|
(C++20) |
向最大堆添加一个元素 (算法函数对象) |