chapter4 序列式容器:priority_queue


1 概述

priority_queue带有权值观念,其内的元素并非依照被推入的次序排列,而是自动依照元素的权值排列(通常权值以实值表示)。权值最高者,排在最前面。

缺省情况下,priority_queue系利用一个max-heap完成,后者是一个vector表现的complete binary tree。max-heap可以满足priority_queue所需要的“依权值高低自动递增排序”的特性。

在这里插入图片描述

2 定义完整列表

priority_queue以vector为底部容器,再加上heap的处理规则。具有这种“修改某物接口,形成另一种风貌”之性质者,称为adapter(配接器),因此,STL priority_queue往往被归类为container adapter。

template<class T, class Sequence = vector<T>, class Compare = less<typename Sequence::value_type>>
class priority_queue {
//...
protected:
    Sequence c;		//底层容器
    Compare comp;	//元素大小比较标准
public:
    priority_queue() : c() {}
    explicit priority_queue(const Compare& x) : c(), comp(x) {}
    
    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)
        : c(first, last) {make_heap(c.begin(), c.end(), comp);}
    
    bool empty() const {return c.empty();}
    //...
    
    void push(const value_type& x) {
        __STL_TRY {
            //push_heap是泛型算法,先利用底层容器的push_back()将新元素推入末端,再重排heap。
        	c.push_back(x);
            push_heap(c.begin(), c.end(), comp);
        }
        __STL_UNWIND(c.clear());
    }
    void pop() {
        __STL_TRY {
            //pop_heap是泛型算法,它并不是真正将元素弹出,而是重排heap,然后再以底层容器的pop_back()取得被弹出的元素
            pop_heap(c.begin(), c.end(), comp);
            c.pop_back();
        }
        __STL_UNWIND(c.clear());
    }
};

3 priority_queue没有迭代器

priority_queue的所有元素,进出都有一定的规则,只有queue顶端的元素(权值最高者),才有机会被外界取用。priority_queue不提供遍历功能,也不提供迭代器

4 示例

#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int arr[5] = {0, 1, 2, 3, 4};
    priority_queue<int> q(arr, arr + 5);
    cout << "size = " << q.size() << endl;

    for (int i = 0; i < q.size(); ++i) {
        cout << q.top() << " ";
    }
    cout << endl;

    while (!q.empty()) {
        cout << q.top() << " ";
        q.pop();
    }
    cout << endl;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值