如何在c++类的STL priority_queue中实现这种比较
How do achieve this comparison in STL priority_queue inside C++ Class
这不是一个重复的问题,这里的区别在于比较函数依赖于主类
我所有的逻辑都在一个类中。我有一张地图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(){}
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 为什么 std::queue 没有实现 insert() 而 std::d eque 实现了?
- 使用Array实现QUEUE
- 栈实现了Queue Peek功能