C++STL--priority_queue(优先队列)

来源:互联网 发布:国内高薪职业 知乎 编辑:程序博客网 时间:2024/06/02 05:08

priority_queue模版类有三个模版参数,第⼀个是元素类型,第⼆个是容器类型,第三个是⽐较算⼦。其中后两者都可以忽略,默认容器为vector,默认算⼦为less,即⼩的往前排,⼤的往后排(出队列时列尾元素先出队)。
定义priority_queue对象:

priority_queue < int > q;priority_queue < pair < int, int >  >  qq; // 注意在两个尖括号之间⼀定要留空格,防⽌误判priority_queue<int, vector<int>, greater<int> > qqq; // 定义⼩的先出队列

priority_queue的基本操作与queue的略微不同。
priority_queue的基本操作:

q.empty() // 如果队列为空,则返回true,否则返回falseq.size() // 返回队列中元素的个数q.pop() // 删除队⾸元素,但不返回其值q.top() // 返回具有最⾼优先级的元素值,但不删除该元素q.push(item) // 在基于优先级的适当位置插⼊新元素

初学者在使⽤priority_queue时,最困难的可能就是如何定义⽐较算⼦了。如果是基本数据类型,或已定义了⽐较运算符的类,可以直接使⽤STL的less算⼦和greater算⼦——默认为使⽤less算⼦。如果要定义⾃⼰的⽐较算⼦,⽅法有多种,这⾥介绍其中⼀种:重载⽐较运算符。优先队列试图这两个元素x和y代⼊⽐较运算符(对于less算⼦,调⽤x < y,对于greater算⼦,调⽤x > y),若结果为真,则x排在y前⾯, y将先出队列,反之,则y排在x前⾯, x将先出队列。
Ex(算⼦实现示例) :

#include <iostream>#include <queue>using namespace std;class T{    public:    int x, y, z;    T(int a, int b, int c) : x(a), y(b), z(c) {}};bool operator < (const T &tOne, const T &tTwo){    return tOne.z < tTwo.z; // 按照z的顺序来决定tOne和tTwo的顺序}int main(){    priority_queue<T> q;    q.push(T(4, 4, 3));    q.push(T(2, 2, 5));    q.push(T(1, 5, 4));    q.push(T(3, 3, 6));    while (!q.empty())    {        T t = q.top();        q.pop();        cout << t.x << " " << t.y << " " << t.z << '\n';    }    return 0;}

/*
* 输出结果为:
* 4 4 3
* 1 5 4
* 2 2 5
* 3 3 6
*/
如果我们将第⼀个例⼦中的⽐较运算符重载为:

bool operator < (const T &tOne, const T &tTwo){return tOne.z > tTwo.z; // 按照z的顺序来决定tOne和tTwo的顺序}

则会得到和第⼆个例⼦⼀样的结果,所以,决定算⼦的是⽐较运算符重载函数内部的返回值。

原创粉丝点击