C++ priority_queue(优先队列)使用

优先队列:优先队列是一个容器,允许对数时间插入的代价,常熟市建的最大值(或者最小值)。
使用STL的std::priority_queue需要包含头文件queue

定义如下:

template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

container默认是vector,compare是比较函数,默认是less,当然可以自己定义比较函数。

常用的函数:

empty()  //如果优先队列为空,则返回真 
pop()    //删除第一个元素 
push()  //插入一个元素 
size()  //返回优先队列中拥有的元素的个数 
top()  //返回优先队列中有最高优先级的元素

测试例子:

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

void print(priority_queue<int> q){
    while (!q.empty()){
        cout << q.top() << " ";
        q.pop();
    }
    cout << endl;
}

int main(){
    priority_queue<int> q;

    for (int n:{1,2,3,4,5,6,7})
        q.push(n);

    cout << q.top() << endl;
    cout << "Is q empty?" <<  q.empty() <<endl;
    print(q);

    cout << "插入:0" << endl;
    q.push(0);
    print(q);

    cout << "删除:" << endl;
    q.pop();
    print(q);

    return 0;
}
ubuntu@VM-188-113-ubuntu:~/test_cpp$ ./priority_queue_test2
7
Is q empty?0
7 6 5 4 3 2 1 
插入:0
7 6 5 4 3 2 1 0 
删除:
6 5 4 3 2 1 0 

自己定义比较函数:

/*
 *本程序测试std::priority_queue的基本用法
 * */

#include <iostream>
#include <functional>
#include <queue>
#include <vector>

using namespace std;

struct Node{
    int f;
    bool operator<(const Node& node) const{
        return f < node.f;
    }
};

class cmp{
    public:
        bool operator()(const Node& n1, const Node& n2) const{
            return n1 < n2;
        }
};

int main(){

    priority_queue<Node, vector<Node>, cmp> q;
    Node n1; n1.f = 5;
    Node n2; n2.f = 4;
    Node n3; n3.f = 3;
    Node n4; n4.f = 2;
    Node n5; n5.f = 1;

    q.push(n1);q.push(n2);q.push(n3);q.push(n4);q.push(n5);

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

    return 0;
}
ubuntu@VM-188-113-ubuntu:~/test_cpp$ ./priority_queue_test
1 2 3 4 5 
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值