C++ STL 堆算法: make_heap(), push_heap(), pop_heap(), sort_heap()

在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 9 
after make_heap, v: 9 5 4 1 2 3 
after pop_heap, v: 5 3 4 1 2 9 
former top element: 9 
after removing the former top element, v: 5 3 4 1 2 
after sort_heap: 1 2 3 4 5 
 
Min heap: 
initially, v1: 3 2 4 1 5 9 
after make_heap, v1: 1 2 4 3 5 9 
after pop_heap, v1: 2 3 4 9 5 1 
former top element: 1 
after removing the former top element, v1: 2 3 4 9 5 
after 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值