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

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,否则返回false
q.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的顺序
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值