C++ 优先队列

最近在 学习贪心算法,发现很多题目都有用到 优先队列,这里特别做了一下整理。

优先队列,顾名思义,就是按照元素的优先级来读取元素,我们可以通过template参数指定一个排序准则。缺省的排序准则是利用operator< 形成降序排列,那么所谓“下一个元素”就是“数值最大的元素”。

C++优先队列类似队列,但是在这个数据结构中的元素按照一定的断言排列有序。
1.empty() 如果优先队列为空,则返回真
2.pop() 删除第一个元素
3.push() 加入一个元素
4.size() 返回优先队列中拥有的元素的个数
5.top() 返回优先队列中有最高优先级的元素

优先级队列可以用向量(vector)或双向队列(deque)来实现(注意list container 不能用来实现queue,因为list 的迭代器不是任意存取iterator,而pop 中用到堆排序时是要求randomaccess iterator 的!):
priority_queue<vector<int>, less<int>> pq1; // 使用递增less<int>函数对象排序
priority_queue<deque<int>, greater<int>> pq2; // 使用递减greater<int>函数对象排序
其成员函数有“判空(empty)” 、“尺寸(Size)” 、“栈顶元素(top)” 、“压栈(push)” 、“弹栈(pop)”等。

这里给出一段运用优先队列的代码,看一下是否会有以上的效果。

//在Xcode下编译通过
#include <iostream>
#include <queue>
using namespace std ;

int main()
{
    priority_queue<float> q;
    
    // insert three elements into the priority queue
    q.push (66.6);
    q.push (22.2);
    q.push (44.4);
    
    // read and print two elements
    cout << q.top () << ' ';
    q.pop ();
    cout << q.top () << endl;
    q.pop ();
    
    // insert three more elements
    q.push (11.1);
    q.push (55.5);
    q.push (33.3);
    
    // skip one element
    q.pop ();
    
    // pop and print remaining elements
    while (!q.empty ()) {
        cout << q.top () << ' ';
        q.pop ();
    }
    cout << endl ;
}

66.6 44.4
33.3 22.2 11.1 
Program ended with exit code: 0




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值