我有我的结构:
struct S{
int a;
};
我有课:
class Other{
//some fields
};
我需要写仿函数:
struct Comparator {
bool operator()(S& l, S& r) {
//some code, considered l,r and any object of class Other
}
};
在 operator() 中应该被认为是 Other 类的任何对象。 如何将对象转换为仿函数? 我将仿函数用于 priority_queue。 Other 类的对象不能是静态字段。
还有其他方法吗?
最佳答案
制作Comparator
存储 Other
类型的对象(或引用 shared_ptr
或 unique_ptr
取决于所有权和有效性语义),并通过 Comparator
传递它的构造函数。
struct Comparator {
Comparator(const Other& val) : mVal(val){}
bool operator()(S& l, S& r)
{
//Comparison code here uses l, r and mVal
}
private:
Other mVal;
};
创建 priority_queue
像这样,假设你想使用 vector<T>
作为底层容器:
Other otherToHelpCompare;
Comparator myComparator{otherToHelpCompare};
std::priority_queue<T, std::vector<T>, Comparator> q{myComparator};
关于c++ - 如何在 std::priority_queue 的仿函数中传输附加对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29967167/