如何在c++类的STL priority_queue中实现这种比较

How do achieve this comparison in STL priority_queue inside C++ Class

本文关键字:queue 实现 比较 priority c++ 类的 STL      更新时间:2023-10-16

这不是一个重复的问题,这里的区别在于比较函数依赖于主类

我所有的逻辑都在一个类中。我有一张地图nodeCnt可以在getCnt()上查到。我正在弄清楚如何为我的优先队列pq定制比较myCmp,它将根据地图进行比较。

下面的代码片段不起作用。并且不能像参考文档中描述的那样使用auto cmp,因为类不能为比较函数声明这样的声明。

Class AllLogic {
 private:
   std::map<int, int> nodeCnt;
   // This is my confusing part
   std::priority_queue<int, std::vector<int>, decltype(&myCmp)> pq(&myCmp);
 public:
   int getCnt(int val) {
     if (nodeCnt.find(val) != nodeCnt.end())
         return nodeCnt[val];  
      return 0;
    }
  bool myCmp(int left, int right) {
     return getCnt(left) < getCnt(right);
  } 
};

创建一个像这样的结构体:

// forward declare your class, because the comparator will use it
class AllLogic;
struct MyCompareT
{
    AllLogic* object;
    bool operator()(int left, int right) const;
};
// after AllLogic has been defined
bool MyCompareT::operator()(int left, int right) const {
    return object->myCmp(left, right);
}

您的priority_queue可以定义为:

std::priority_queue<int, std::vector<int>, MyCompareT> pq;

并在构造函数中这样初始化:

AllLogic() :pq(MyCompareT{this}) {}

您可以将代码稍微修改一下,如下所示(注意:以下是c++11):

#include <map>
#include <queue>

比较函子接受对map的引用,并使用它进行比较:

struct myCmp {
    explicit myCmp(std::map<int, int> &nodeCnt) : nodeCnt_{&nodeCnt} {}
    bool operator()(int lhs, int rhs) const {
        auto lhs_it = nodeCnt_->find(lhs);
        auto rhs_it = nodeCnt_->find(rhs);
        auto lhs_val = lhs_it == nodeCnt_->end()? 0: lhs_it->second;
        auto rhs_val = rhs_it == nodeCnt_->end()? 0: rhs_it->second;
        return lhs_val < rhs_val; 
    }
private:
   std::map<int, int> *nodeCnt_;
};

类先设置map,然后设置比较函子,然后设置队列;每个都使用前一个:

class AllLogic {
private:
   std::map<int, int> nodeCnt;
   myCmp myCmp_{nodeCnt};
   std::priority_queue<int, std::vector<int>, myCmp> pq{myCmp_};
};
int main(){}