C++STL优先级队列priority_queue

优先级队列priority_queue

默认使用vector作为容器,底层数据结构为堆。

操作函数与stack一样。

priority_queue<int> a;   //默认为最大值优先级队列,即top元素最大。
a.push(5);
a.pop();
a.top();
a.empty();  //判断是否为空

可以自定义优先级:

priority_queue<int, vector<int>, cmp> p;

注:使用less或greater需要#include<functional>

#include<functional>
priority_queue<int, vector<int>, less<int>> p;  //最大值优先级队列
priority_queue<int, vector<int>, greater<int>> p;  //最小值优先级队列

定义cmp:

struct cmp
{
    bool operator()(int &a, int &b) const
    {
        return a > b;  //最小值优先
    }
};

struct cmp
{
    bool operator()(int &a, int &b) const
    {
        return a < b;  //最大值优先
    }
};


优先级队列的应用:定义一个元素为pair的优先级队列,自定义比较函数,使队列按照pair.first的大小排列,如果pair.first相等,则按照pair.second的大小排列。

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

struct cmp
{
    bool operator()(pair<int, int>&a, pair<int, int>&b) const
    {
        if(a.first == b.first) return a.second > b.second;
        else return a.first < b.first;
    }
};

int main(){
	int n;
	cin >> n;
	priority_queue<pair<int, int>, vector<pair<int, int> >, cmp> p;
	for(int i = 0; i < n; ++i){
		int first, second;
		cin >> first >> second;
		p.push(make_pair(first, second));
	}
    while(p.size()){
        cout << p.top().first << ' ' << p.top().second << endl;
        p.pop();
    }
	return 0;
}

输出结果如下:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值