c++ - 需要访问类私有(private)成员的比较器

标签 c++ algorithm stl

我的代码的基本结构是

class Foo{
  vector<string> _lines;
  vector<int> _n;
  public:
  ...
  bool Comp(int i, int j){
    return something that depends on _lines;
  }
  ...
  void doSomething(){
    std::sort(_n.begin(), _n.end(), Comp);
  }
  ...
};

但是我明白了

error: no matching function for call to 
‘sort(std::vector<unsigned int>::iterator, 
std::vector<unsigned int>::iterator, <unresolved overloaded function type>)

如何不复制 vector 来解决这个问题?(因为这些 vector 非常大,准确地说是 17179508 个字符串)。

最佳答案

std::sort 在这种情况下期望二元谓词采用两个整数。成员函数采用隐式第一个参数,因此在所有 Foo::Comp 中采用三个参数。您可以传递非成员函数或静态成员函数,但它们都无法访问 Foo 的数据成员。最简单的方法是使用 std::bindthis 绑定(bind)到成员函数的第一个参数:

#include <functional> // for std::bind
#include <vector>
#include <algorithm>

class Foo{
  vector<string> _lines;
  vector<int> _n;
 public:
  ...

  bool Comp(int i, int j){
    return something that depends on _lines;
  }
  ...
  void sort(){
    using namespace std::placeholders;
    std::sort(_n.begin(), _n.end(), std::bind(Comp, this, _1, _2));
  }
  ...
};

关于c++ - 需要访问类私有(private)成员的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16901415/

相关文章:

c++ - 找到数字属于哪个部分的快速方法是什么(在 C++ 中使用 vector )?

c++ - 是为每个对象创建单独的函数还是为每个类创建一个函数?

c++ - std::condition_variable 内存写入可见性

c - 以 256 为基数的算术

c++ - 如何在C++中比较std::array?

c++ - 正确的方法返回STL容器

c++ - 读取整个 std::ifstream 到堆

java - 使用小数据类型是否会减少内存使用(来自内存分配而不是效率)?

algorithm - 带内存的尾递归 pow() 算法?

objective-c - 如何使用 Objective C 反转单链表