This site建议如果我想反向排序我的优先级队列,我应该使用以下代码:
#include <iostream>
#include <queue>
using namespace std;
class mycomparison{
bool reverse;
public:
mycomparison(const bool &revparam=false) {reverse=revparam;}
bool operator() (const int &lhs, const int &rhs) const {
if (reverse) return (lhs>rhs);
else return (lhs<rhs);
}
};
int main (){
int myints[]= {10,60,50,20};
priority_queue<int, vector<int>, mycomparison(true)> first;
return 0;
}
这困扰我:
是否有更优雅或更简洁的反向排序优先级队列的方式?
答案 0 :(得分:17)
您无法避免指定存储容器,但可以避免编写自己的仿函数:
priority_queue<int, vector<int>, std::greater<int> > first;
答案 1 :(得分:0)
如果您需要灵活性而无需定义任何类,则可以使用std::function>
作为比较器的类型:
#include <functional>
int main ()
{
int myints[]= {10,60,50,20};
// Use this is a the type of your comparator
typedef std::function<bool(int, int)> comp_type;
// Priority queue using operator < for ordering
priority_queue<int, vector<int>, comp_type> first(std::less<int>());
// ...
// Priority queue using operator > for ordering
priority_queue<int, vector<int>, comp_type> second(std::greater<int>());
// ...
return 0;
}
答案 2 :(得分:0)
当我反转struct的优先级队列时,我发现了更简单的解决方案。 我从那里修改了解决方案:stl priority_queue of C++ with struct
struct leaf
{
int symbol;
double probability;
bool operator < (const leaf &o) const
{
return probability > o.probability; // here just reversed the operator
}
};
priority_queue <leaf> leafs_queue; //queue already reversed