C++ STL 优先队列
优先队列特点:除了有与队列相同的先进先出的特点之外,优先队列还有自动排序的特点。
优先队列基本定义方式:
1、priority_queue<数据类型>队列名称,例:
2、priority_queue<结构体>队列名称,例:
该结构体中重载了< 方法
3、priority_queue<int,vector<>int ,greater(less)<int> >队列名称
优先队列常用方法:
优先队列实现:
1、priority_queue<数据类型>队列名称,例:
#include<cstdio>
#include<queue>
using namespace std;
int main(){
priority_queue<int>p;
priority_queue<char>q;
p.push(2);p.push(1);p.push(12);p.push(5);p.push(8);
q.push('a');q.push('c');q.push('x');q.push('b');q.push('d');
while(!p.empty()){
printf("%d ",p.top()),p.pop();
}
printf("\n");
while(!q.empty()){
printf("%c ",q.top()),q.pop();
}
return 0;
}
运行结果:默认从大到小降序排序
2、priority_queue<结构体>队列名称,例:
#include<cstdio>
#include<queue>
using namespace std;
struct node{
int x;
bool operator < (const node & a)const{
return x<a.x;
}
}a;
int main(){
//node是结构体,重载 <
priority_queue<node>p1;
a.x = 2;p1.push(a);
a.x = 1;p1.push(a);
a.x = 12;p1.push(a);
a.x = 5;p1.push(a);
a.x = 8;p1.push(a);
while(!p1.empty())
printf("%d ",p1.top()),p1.pop();
return 0;
}
运行结果:降序
3、greater<>与less<>,例:
#include<cstdio>
#include<queue>
using namespace std;
int main(){
priority_queue<int,vector<int>,greater<int> >q1;//此处注意最右边的两个>要用空格隔开,>>是右移符
priority_queue<int,vector<int>,less<int> >q2;
int a[] = {2,1,12,5,8};
for(int i=0;i<5;i++)
q1.push(a[i]),q2.push(a[i]);
printf("greater<>:");
while(!q1.empty())
printf("%d ",q1.top()),q1.pop();
printf("\nless<>:");
while(!q2.empty())
printf("%d ",q2.top()),q2.pop();
return 0;
}
运行结果:
总结:
优先队列默认排序为降序排序,
而greater<>与less<>分别升序(从小到大)和降序(从大到小)。