std::ranges::make_heap
来自cppreference.com
| 在标头 <algorithm> 定义
|
||
| 调用签名 |
||
| template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > |
(1) | (C++20 起) |
| template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > |
(2) | (C++20 起) |
在范围 [first, last) 中构造最大堆。
1) 用给定的二元比较函数 comp 与投影对象 proj 比较元素。
此页面上描述的函数式实体是 niebloid,即:
实践中,可以作为函数对象,或者用某些特殊编译器扩展实现它们。
参数
| first, last | - | 要做出堆的元素范围 |
| r | - | 要做出堆的元素范围 |
| pred | - | 应用到投影后元素的谓词 |
| proj | - | 应用到元素的投影 |
返回值
等于 last 的迭代器。
复杂度
给定 N = ranges::distance(first, last),至多 3•N 次比较,6•N 次投影。
注解
最大堆 是按照比较器 comp 与投影 proj 排列的元素范围 [f, l),拥有下列属性:
- 令
N == l - f,对于所有0 < i < N,p = f[(i - 1) / 2]且q = f[i],表达式 std::invoke(comp, std::invoke(proj, p), std::invoke(proj, q)) 求值为 false。 - 能用 ranges::push_heap() 在 𝓞(log N) 时间内添加新元素。
- 能用 ranges::pop_heap() 在 𝓞(log N) 时间内移除首元素。
- 令
示例
运行此代码
#include <algorithm> #include <cmath> #include <functional> #include <iostream> #include <vector> void out(const auto& what, int n = 1) { while (n-- > 0) std::cout << what; } void print(auto rem, auto const& v) { out(rem); for (auto e : v) out(e), out(' '); out('\n'); } void draw_heap(auto const& v) { auto bails = [](int n, int w) { auto b = [](int w) { out("┌"), out("─", w), out("┴"), out("─", w), out("┐"); }; if (!(n /= 2)) return; for (out(' ', w); n-- > 0;) b(w), out(' ', w + w + 1); out('\n'); }; auto data = [](int n, int w, auto& first, auto last) { for (out(' ', w); n-- > 0 && first != last; ++first) out(*first), out(' ', w + w + 1); out('\n'); }; auto tier = [&](int t, int m, auto& first, auto last) { const int n{1 << t}; const int w{(1 << (m - t - 1)) - 1}; bails(n, w), data(n, w, first, last); }; const int m{static_cast<int>(std::ceil(std::log2(1 + v.size())))}; auto first{v.cbegin()}; for (int i{}; i != m; ++i) tier(i, m, first, v.cend()); } int main() { std::vector h{1, 6, 1, 8, 0, 3, 3, 9, 8, 8, 7, 4, 9, 8, 9}; print("source: ", h); std::ranges::make_heap(h); print("\n" "最大堆: ", h); draw_heap(h); std::ranges::make_heap(h, std::greater{}); print("\n" "最小堆: ", h); draw_heap(h); }
输出:
源: 1 6 1 8 0 3 3 9 8 8 7 4 9 8 9
最大堆: 9 8 9 8 8 4 9 6 1 0 7 1 3 8 3
9
┌───┴───┐
8 9
┌─┴─┐ ┌─┴─┐
8 8 4 9
┌┴┐ ┌┴┐ ┌┴┐ ┌┴┐
6 1 0 7 1 3 8 3
最小堆: 0 1 1 8 6 3 3 9 8 8 7 4 9 8 9
0
┌───┴───┐
1 1
┌─┴─┐ ┌─┴─┐
8 6 3 3
┌┴┐ ┌┴┐ ┌┴┐ ┌┴┐
9 8 8 7 4 9 8 9参阅
| (C++20) |
检查给定范围是否为最大堆 (niebloid) |
| (C++20) |
寻找能成为最大堆的最大子范围 (niebloid) |
| (C++20) |
将一个元素加入到一个最大堆 (niebloid) |
| (C++20) |
从最大堆中移除最大元素 (niebloid) |
| (C++20) |
将一个最大堆变成一个按升序排序的元素范围 (niebloid) |
| 从一个元素范围创建出一个最大堆 (函数模板) |