c++ - 定义映射/集合时如何实例化比较函数(仿函数)?

标签 c++ std functor multiset

我正在使用函数对象来指定映射/集合的比较函数:

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/

相关文章:

haskell - 什么是在一个被调用的元组上分配一个仿函数?

module - 在 OCaml 中使用一流模块

c++ - 在 GitHub 中,如何在 "RecoverCompact"中搜索 "CPubKey::RecoverCompact"

c++ - wxwidgets 中的按钮 - 不同的行为

c++ - fgets 与 std::fgets - fgets 错过了行

c++ - 如何返回 std::map 项目

c++ - 从 std::FILE* 创建 GIO GFile 或 GInputStream

c++ - 在 dll 中导出函数。 C 和 C++

c++ - Visual Studio std::stringstream pubsetbuf 不起作用

C++ 理解仿函数多态性