我正在使用函数对象来指定映射/集合的比较函数:
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’ cannot appear in a constant-expression
你有什么想法可以解决这个问题吗?
最佳答案
您可以将仿函数的实例作为参数传递给集合构造函数。所以像 multiset<Node*, CompareObject> shapesSet(CompareObject(myTree));
关于c++ - 定义映射/集合时如何实例化比较函数(仿函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19218536/