STL 学习总结七 —— heap && priority_queue

heap && priority_queue

heap (堆)

建立在完全二叉树上,分为两类:大根堆小跟堆, 其在STL中做priority_queue的助手,即以任何顺序将元素推入容器中,然后取出一定是从优先权最高的元素开始取,完全二叉树具有这样的性质,适合做priority_queue的底层。

堆,图片来源于代码随想录

priority_queue(优先队列)

优先队列, 也是适配器。其内的元素不是按照被推入的顺序排序,而是自动取元素的权值排序,缺省情况下利用一个max_heap完成,后者是以vector表示的完全二叉树。

template<class T, class Sequence=vector <T>, class Compare=less<typename
Sequence::value_type>>
class priority_queue {
public:
    typedef typename Sequence::value_type value_type;
    typedef typename Sequence::size_type size_type;
    typedef typename Sequence::reference reference;
	typedef typename Sequence::const_reference const_refernece;

protected:
    Sequence c;//底层容器
    Compare comp//容器⽐较⼤⼩标准

public:
    priority_queue() : c() {}
    explicit priority_queue(const Compare &x) : c(), comp(x) {}
    //以下⽤到的make_heap(),push_heap(),pop_heap()都是泛型算法
    
    //任何⼀个构造函数都可以⽴即在底层产⽣⼀个heap
    template<class InputIterator>
    priority_queue(InputIterator first, InputIterator last const Compare &x) :c(first, last), comp(x) { make_heap(c.begin(), c.end(), comp); }
    template<class InputIterator>
    priority_queue(InputIterator first, InputIterator last const Compare &x) :c(first, last) { make_heap(c.begin(), c.end(), comp); }
    
    bool empty() const { return c.empty(); }
    size_type size() const { return c.size(); }
    const_reference top() const { return c.front(); }
    void push(const value_type &x) {
   		_STL_TRy {
            c.push_back(X);
            push_heap(c.begin(), c.end(), comp);
    	}
    	_STL_UNWIND{c.clear()};
    }
    
    void pop() {
        _STL_TRY {
        pop_heap(c.begin(), c.end(), comp);
        c.pop_back();
    }
    _STL_UNWEIND{c.clear()};
    }
};
// priority_queue⽆迭代器
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

L☆★

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值