优先级队列的反向顺序

Priority queue in reverse order

本文关键字:顺序 队列 优先级      更新时间:2023-10-16

本站点建议,如果我想对优先级队列进行反向排序,我应该使用以下代码:

#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