priority_queue

priority_queue

priority_queue就是一个堆,并且默认情况下位大根堆。

priority_queue函数列表
函数描述      by MoreWindows( http://blog.csdn.net/MoreWindows )
构造析构 
priority_queue <Elem> c 创建一个空的queue 。
注:priority_queue构造函数有7个版本,请查阅MSDN
数据访问与增减 
c.top()返回队列头部数据
c.push(elem)在队列尾部增加elem数据
 c.pop()队列头部数据出队
其它操作 
c.empty()判断队列是否为空
c.size()

返回队列中数据的个数

  

可以看出priority_queue的函数列表与栈stack的函数列表是相同的。

priority_queue优先队列,插入进去的元素都会从大到小排好序

PS:在priority_queue<ll, vector<ll>, greater<ll> > pq;中
第一个参数为数据类型,第二个参数为保存数据的容器(默认为vector<int>),第三个参数为元素比较函数(默认为less)。

 

STL里面默认用的是 vector. 比较方式默认用 operator< , 所以如果你把后面俩个参数缺省的话,
优先队列就是大顶堆,队头元素最大。

 

更多细节看实例吧:

 

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 priority_queue<int> q1;
 4 priority_queue<int,vector<int>,greater<int> > q2;
 5 priority_queue<int,vector<int>,less<int> > q3;//默认为less,是大根堆 
 6 
 7 struct node{ 
 8     int a; 
 9     int b;
10     node(int a,int b){
11         this->a=a;
12         this->b=b;
13     }
14 }; 
15 struct myCmp{
16     bool operator ()(const node &p1,const node &p2){//这里是取引用 ,而且这里重载的是括号而不是<号 
17         return p1.a<p2.a;
18     }
19 };
20 
21 priority_queue<node,vector<node>,myCmp > q4;
22 
23 int main(){
24     int a[7]={1,9,5,7,8,11,4};
25     
26     for(int i=0;i<7;i++) q1.push(a[i]);
27     cout<<q1.top()<<endl;//输出为11,所以默认为大根堆
28     
29     for(int i=0;i<7;i++) q2.push(a[i]);
30     cout<<q2.top()<<endl;//输出为1,说明greater加持之后变成了小根堆    
31 
32     for(int i=0;i<7;i++) q3.push(a[i]);
33     cout<<q3.top()<<endl;//输出为11,说明是大根堆,默认就为less        
34     
35     int h[3][2]={{1,3},{3,2},{2,1}}; 
36     for(int i=0;i<3;i++) {
37         int a=h[i][0];
38         int b=h[i][1];
39         q4.push(node(a,b));
40     }
41     node p=q4.top();
42     cout<<p.a<<" "<<p.b<<endl;//输出为3 2,说明是按a成员来的大根堆,我定义的时候是定义的小于,也就是相当于less 
43     
44     return 0;
45 } 

 关于代码说几点:

1、构造函数

2、重载()

3、满足比较条件的元素往后走了

4、比较部分要是结构体

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值