优先队列和堆一样有两种形式:最大优先队列和最小优先队列。
1.如果直接定义一个优先队列,系统默认的为降序优先队列。
priority_queue<int > pq;
2. 可以通过系统默认的已有的结构greater<T>来定义一个升序的优先队列。与greater<T>类似的是less<T>。
#include <iostream> #include<queue> #include<ctime> #include<cstdlib> #include<vector> using namespace std; int main() { srand(time(NULL)); priority_queue<int,vector<int>,greater<int> > pq; for(int i=10;i>0;i--) { pq.push(rand()); } while(!pq.empty()) { cout<<pq.top()<<endl; pq.pop(); } return 0; }
3.如果队列元素为某结构体,可以通过重载<符号来进行自定义优先级,这里必须要注意的是只能是<并且在重载函数还需要加上const!
#include <iostream> #include<queue> #include<ctime> #include<cstdlib> #include<vector> using namespace std; struct node { int data; bool operator <(const node a)const //!!! { return data>a.data; //此时是升序,如果是<则是降序 } }; int main() { srand(time(NULL)); priority_queue<node > pq; for(int i=10;i>0;i--) { node t; t.data=rand(); pq.push(t); } while(!pq.empty()) { cout<<pq.top().data<<endl; pq.pop(); } return 0; }
4.结构体定义优先级还有种方式,可以不加const,但需要定义为友元。
struct node { int data; friend bool operator <(const node a,const node b) //!!! { return a.data>b.data; //此时是升序,如果是<则是降序 } };
5.对于结构体的定义,当在使用优先级定义时,根据其是堆的特性,还可以有如下定义优先级的方式。
#include <iostream> #include<queue> #include<ctime> #include<cstdlib> #include<vector> using namespace std; struct node { int data; }; struct nodeCmp { bool operator()(const node &a,const node &b) { return a.data>b.data; //此时为升序,<为降序 } }; int main() { srand(time(NULL)); priority_queue<node,vector<node>,nodeCmp> pq; //此处定义与之前方式不同 for(int i=10;i>0;i--) { node t; t.data=rand(); pq.push(t); } while(!pq.empty()) { cout<<pq.top().data<<endl; pq.pop(); } return 0; }