优先队列priority_queue(c++)

priority_queue

(个人学习记录用,有问题感谢指正 orz)

priority_queue<type, container, cmp >
// type为数据类型,container为容器类型(默认vector),cmp为排序方式(默认降序)

0.创建优先队列

priority_queue<int>pq;
== priority_queue<int,vector<int> >pq;   
== priority_queue<int,vector<int>,less<int> >pq;
priority_queue<int,vector<int>,greater<int> >pq;
priority_queue<int,vector<int>,cmp >pq;
priority_queue<node,vector<node>,cmp >pq;
priotity_queue<node >pq;
== priority_queue<node,vector<node> >pq;

1.基本操作

top() 访问队头元素
pop() 弹出队头元素
empty() 空返回0,否则返回1
size() 返回队列内元素个数
push(1)    push({1,2})  插入元素到队尾 (并排序)
swap(pq1,pq2) 交换两个队列

2.遍历优先队列

while(!pq.empty()){
	cout<<pq.top()<<endl;
	//cout<<pq.top().x<<" "<<pq.top().y<<endl;
	pq.pop();
}

3.自定义优先级

法一、重写仿函数:
(1) 一元

struct cmp{
  bool operator()(int x, int y)
  {
     return x>y;
  }
};

(2) 多元

struct node
{
    int x,y;
};
struct cmp
{
    bool operator()(node &a,node &b)
    {
    	if(a.x==b.x)return a.y<b.y;
        return a.x<b.x;
        //此处为x相等时,y大的优先级高,否则是x大的优先级高,根据所需写
    }
};

法二、运算符重载:
(1)一元

struct node{
	int x;
	bool operator<(const node a)const
	{
		return x<a.x;
	}
};

(2)多元

struct node{
	int x,y;
	bool operator<(const node a)const
	{
		if(x==a.x)return y>a.y;
		return x>a.x; 
	}
}

4.测试代码

#include<bits/stdc++.h>
#include<queue>
using namespace std;

//struct node{
//	int x,y;
//};

//struct cmp{
//	bool operator()(int x,int y){
//		return x>y;
//	}
//};

//struct cmp{
//	bool operator()(node &a,node &b){
//		if(a.x==b.x)return a.y<b.y;
//		return a.x<b.x;
//	}
//};

struct node{
	int x,y;
	bool operator < (const node a)const
	{
		if(x==a.x)return y>a.y;
		return x>a.x;
	}
};

int main(){
//	priority_queue<int,vector<int>,cmp >pq;
	priority_queue<node,vector<node> >pq;
//	pq.push({1});
//	pq.push({4});
//	pq.push({9});
//	pq.push({3});
	pq.push({1,2});
	pq.push({1,3});
	pq.push({9,1});
	pq.push({3,6});
	while(!pq.empty()){
		cout<<pq.top().x<<" "<<pq.top().y<<endl;
		pq.pop();
	}
//	while(!pq.empty()){
//		cout<<pq.top().x<<endl;
//		pq.pop();
//	}
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值