std::sort_heap() 算法
- 自 C++20 起
- 直到 C++20
template< class RandomIt >
constexpr void sort_heap( RandomIt first, RandomIt last );
// (2)
template< class RandomIt, class Compare >
constexpr void sort_heap( RandomIt first, RandomIt last, Compare comp );
template< class RandomIt >
void sort_heap( RandomIt first, RandomIt last );
// (2)
template< class RandomIt, class Compare >
void sort_heap( RandomIt first, RandomIt last, Compare comp );
将最大堆 [first
; last
) 转换为升序排序范围。
结果范围不再具有堆属性。
-
(1) 元素使用
operator<
进行比较。 -
(2) 元素使用给定的二元比较函数
comp
进行比较。
参数
first last | 要排序的元素范围。 |
policy | 要使用的执行策略。有关详细信息,请参阅执行策略。 |
comp | 比较函数对象(即满足 Compare 要求的对象)。比较函数的签名应等同于以下内容:
|
类型要求
RandomIt | LegacyRandomAccessIterator LegacyRandomAccessIterator |
解引用 RandomIt 的类型 | MoveAssignable MoveConstructible |
返回值
(无)
复杂度
给定 N
为 std::distance(first, last)
最多 2 * N * log(N) 次比较。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数执行抛出异常,并且
ExecutionPolicy
是标准策略之一,则调用std::terminate
。对于任何其他ExecutionPolicy
,行为是实现定义的. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
可能的实现
sort_heap(1)
template<class RandomIt>
void sort_heap(RandomIt first, RandomIt last)
{
while (first != last)
std::pop_heap(first, last--);
}
sort_heap(2)
template<class RandomIt, class Compare>
void sort_heap(RandomIt first, RandomIt last, Compare comp)
{
while (first != last)
std::pop_heap(first, last--, comp);
}
备注
最大堆是具有以下属性的元素范围 [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)) 时间内移除第一个元素。
示例
Main.cpp
#include <algorithm>
#include <iostream>
#include <string_view>
#include <vector>
void println(std::string_view fmt, auto const& v)
{
for (std::cout << fmt; const auto &i : v)
std::cout << i << ' ';
std::cout << '\n';
}
int main()
{
std::vector<int> v {3, 1, 4, 1, 5, 9};
std::sort_heap(v.begin(), v.end());
println("after sort_heap, v: ", v);
std::sort_heap(v.begin(), v.end());
println("after sort_heap, v: ", v);
}
输出
after sort_heap, v: 9 4 5 1 1 3
after sort_heap, v: 1 1 3 4 5 9