如何在定义地图/集时实例化比较函数(仿函数)?

时间:2013-10-07 06:43:52

标签: c++ std functor multiset

我正在使用funciton对象为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'不能出现在常量表达式中

您对如何解决此问题有任何想法吗?

1 个答案:

答案 0 :(得分:4)

您可以将仿函数的实例作为参数传递给集合构造函数。像multiset<Node*, CompareObject> shapesSet(CompareObject(myTree));

这样的东西