我的代码的基本结构是
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::bind
将 this
绑定(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/