我使用函数对象为map/set指定比较函数:
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”不能出现在常量表达式中。
你有什么办法解决这个问题吗?
发布于 2013-10-07 06:48:33
您可以将函子的一个实例作为参数传递给set构造函数。所以有点像multiset<Node*, CompareObject> shapesSet(CompareObject(myTree));
https://stackoverflow.com/questions/19218536
复制相似问题