C++ 倒序优先队列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15647162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Priority queue in reverse order
提问by Richard
This sitesuggests that if I want to reverse-order my priority queues, the following code is what I should use:
该站点建议,如果我想对优先级队列进行反向排序,则应使用以下代码:
#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;
}
This bothers me:
这让我很困扰:
- I have to specify the storage class in my constructor.
- I have created a class whose onlypurpose is to be passed to the priority queue.
- 我必须在我的构造函数中指定存储类。
- 我创建了一个类,其唯一目的是传递给优先级队列。
Is there a more elegant or less verbose way of reverse-sorting a priority queue?
是否有更优雅或更简洁的方式来对优先队列进行反向排序?
回答by juanchopanza
You can't avoid specifying the storage container, but you can avoid writing your own functor:
您无法避免指定存储容器,但您可以避免编写自己的函子:
priority_queue<int, vector<int>, std::greater<int> > first;
回答by Andy Prowl
If you want flexibility without having to define any class, you could use std::function>
as the typeof your comparator:
如果您想要灵活性而不必定义任何类,您可以将其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;
}