我一直很不擅长队列什么的,联赛靠近,必须恶补一下。
首先,使用优先队列必须引用
#include<queue>
定义的时候,有两种。
1.元素大的优先priority_queue<int> pq;
2.元素小的优先 priority_queue<int, vector<int>, greater<int> >pq;
下面列举一些常用操作
1.back() 返回一个引用,指向最后一个元素
2.empty() 如果队列空则返回真
3.front() 返回第一个元素
4.pop() 删除第一个元素
5.push() 在末尾加入一个元素
6.size() 返回队列中元素的个数
是和大多数据结构一样的。
如果只是单纯的对存整数的数组进行排序,直接定义并使用即可。
priority_queue<int> q;
for(i = 0; i < len; i++) q.push(a[i]);
for(i = 0; i < len; i++){cout<<q.top()<<" ";q.pop();}
相当好用,插入加取出等操作。
但是如果有很多成员变量,只有一个需要优先级,则如此定义:(friend不能省略)
struct node{
friend bool operator< (node n1, node n2)
{
return n1.priority < n2.priority;
}
int priority;
int other_element;
};
然后使用的时候
priority_queue<node> qn;
node b[len];
for(i = 0; i < len; i++) qn.push(b[i]);
for(i = 0; i < len; i++){ cout<<qn.top().priority<<" <<qn.top().value<<endl;qn.pop();}