优先级队列的反向顺序
Priority queue in reverse order
本站点建议,如果我想对优先级队列进行反向排序,我应该使用以下代码:
#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;
}
这让我很困扰:
- 我必须在构造函数中指定存储类。我已经创建了一个类,它的只有的目的是传递给优先级队列。
是否有一种更优雅或更简洁的方式来对优先级队列进行反向排序?
不能避免指定存储容器,但可以避免编写自己的函子:
priority_queue<int, vector<int>, std::greater<int> > first;
如果您想要灵活性而不必定义任何类,您可以使用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;
}
我发现了更简单的解决方案,而我正在逆转结构的优先级队列。我从那里修改了解决方案:stl priority_queue的c++与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
相关文章:
- boost::进程间消息队列引发错误
- CMake-按正确顺序将项目与C运行时对象文件链接
- 我已经做了一个程序来使用队列链C++表显示学生姓名和身高,现在我想以我不知道如何显示的顺序显示它
- 如何以相反的顺序将整个向量复制到队列中
- 队列顺序中的链接列表
- C++优先级队列不遵循 FIFO 顺序
- 使用队列在二进制树中的水平顺序遍历
- C++ 中的优先级队列在 pop() 之后顺序不正确
- 按特定顺序打印队列
- 以正确的顺序输出队列
- STL 优先级队列按递增顺序排列
- C++队列中读/写操作的顺序
- 在同一优先级队列中创建递增和递减顺序选项
- 对的优先级队列以相反的顺序排列
- 使用容量受限的队列按顺序列出字符串
- 反转优先级队列中元素的顺序
- 优先级队列的反向顺序
- 互斥锁所有权队列顺序
- 从相同的结构体以相反的顺序创建两个优先级队列
- Qt队列连接中的插槽调用顺序