我正在使用函数对象来指定地图/集的比较函数:
struct CompareObject {
bool operator()(Node* const n1, Node* const n2) const;
};
据我了解,定义这样的集合不会创建任何 CompareObject 实例,并且会假装它是静态的:
std::multiset<Node*, CompareObject> set;
但是在我的问题中,我需要将 Tree 的实例传递给它,因为我在实际的比较函数中使用它:
bool
CompareObject::operator()(Node* const n1, Node* const n2) const {
if (tree->getNoOfGood(n1) > tree->getNoOfGood(n2)) return false;
if (tree->getNoOfGood(n2) > tree->getNoOfGood(n1)) return true;
return false;
}
所以,我在 CompareObject 定义中添加了一些字段:
struct CompareObject {
Tree& tree; // added
CompareObject(Tree& t); // added
bool operator()(Node* const n1, Node* const n2) const;
};
我遇到的问题是我不知道如何用集合的定义来实例化这个对象。
我首先想到的是:
std::multiset<Node*, CompareObjects(*this)> shapesMap; // not valid code
但不出所料,它给了我一个错误:“this”不能出现在常量表达式中
您对如何解决这个问题有任何想法吗?