在c++20中引入了几个堆相关的算法:make_heap(), push_heap(), pop_heap(), sort_heap(), is_heap, is_heap_until(),现在来开始介绍这几个函数和写一个示例。
make_heap | 在一个迭代器范围内构造一个堆(默认最大堆) |
push_heap | 往一个元素插入到堆的末尾的下一个位置 |
pop_heap | 弹出堆顶元素,并把它放到末尾位置 |
sort_heap | 把一个堆进行排序 |
is_heap | |
is_heap_until |
make_heap(),pop_heap(), sort_heap()的使用示例
#include <algorithm>
#include <functional>
#include <iostream>
#include <string_view>
#include <vector>
void print(std::string_view text, std::vector<int> const& v = {}) {
std::cout << text << ": ";
for (const auto& e : v) std::cout << e << ' ';
std::cout << '\n';
}
int main()
{
print("Max heap");
std::vector<int> v { 3, 2, 4, 1, 5, 9 };
print("initially, v", v);
std::make_heap(v.begin(), v.end());
print("after make_heap, v", v);
std::pop_heap(v.begin(), v.end());
print("after pop_heap, v", v);
auto top = v.back();
v.pop_back();
print("former top element", {top});
print("after removing the former top element, v", v);
sort_heap(v.begin(), v.end(), std::less<>());
print("after sort_heap", v);
print("\nMin heap");
std::vector<int> v1 { 3, 2, 4, 1, 5, 9 };
print("initially, v1", v1);
std::make_heap(v1.begin(), v1.end(), std::greater<>{});
print("after make_heap, v1", v1);
std::pop_heap(v1.begin(), v1.end(), std::greater<>{});
print("after pop_heap, v1", v1);
auto top1 = v1.back();
v1.pop_back();
print("former top element", {top1});
print("after removing the former top element, v1", v1);
sort_heap(v.begin(), v.end(), std::greater<>());
print("after sort_heap", v);
}
输出如下:
Max heap:initially, v: 3 2 4 1 5 9after make_heap, v: 9 5 4 1 2 3after pop_heap, v: 5 3 4 1 2 9former top element: 9after removing the former top element, v: 5 3 4 1 2after sort_heap: 1 2 3 4 5Min heap:initially, v1: 3 2 4 1 5 9after make_heap, v1: 1 2 4 3 5 9after pop_heap, v1: 2 3 4 9 5 1former top element: 1after removing the former top element, v1: 2 3 4 9 5after sort_heap: 5 4 3 2 1
push_heap()示例
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> v { 3, 1, 4, 1, 5, 9 };
std::make_heap(v.begin(), v.end());
std::cout << "v: ";
for (auto i : v) std::cout << i << ' ';
std::cout << '\n';
v.push_back(6);
std::cout << "before push_heap: ";
for (auto i : v) std::cout << i << ' ';
std::cout << '\n';
std::push_heap(v.begin(), v.end());
std::cout << "after push_heap: ";
for (auto i : v) std::cout << i << ' ';
std::cout << '\n';
}
v: 9 5 4 1 1 3 before push_heap: 9 5 4 1 1 3 6 after push_heap: 9 5 6 1 1 3 4