sách gpt4 ăn đã đi

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

In lại 作者:太空狗 更新时间:2023-10-29 20:54:16 25 4
mua khóa gpt4 giày nike

这不是一个重复的问题,这里有所不同,因为比较函数依赖于主类。

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

以下代码段不起作用。并具有如 reference docs 中所述的 auto cmp不能这样做,因为类不能有这样的比较功能声明。

Class AllLogic {

riêng tư:
std::map nodeCnt;

// This is my confusing part
std::priority_queue, decltype(&myCmp)> pq(&myCmp);

công cộng:

int getCnt(int val) {
if (nodeCnt.find(val) != nodeCnt.end())
return nodeCnt[val];
trả về 0;
}

bool myCmp(int left, int right) {
return getCnt(left) < getCnt(right);
}
};

câu trả lời hay nhất

做一个这样的结构:

// 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, MyCompareT> pq;

并在构造函数中初始化如下:

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

关于c++ - 如何在 C++ 类中的 STL priority_queue 中实现这种比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39811555/

25 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress