我正在编写代码来解决以下问题:给定一组数字 x[0]
, x[1]
, ..., x[N-1]
, 找到使它们按升序排序的排列。换句话说,我想在 {0,2,...,N-1} 上找到一个排列,例如 i[0]
, i[1]
, ..., i[N-1]
这样 x[i[0]] <= x[i[1]] <= ... <= x[i[N-1]]
.
为此,我存储了 x
vector 和索引 vector i
(最初填充为 i[j] = j
)作为类的私有(private)成员。我还将一个私有(private)方法定义为
bool MyClass::compare(size_t s, size_t t) {
return (x[s] < x[t]);
}
现在,我会调用 std::sort
如下
std::sort(i.begin(), i.end(), compare);
我希望得到想要的结果。但是代码没有编译,我收到以下错误:
error: no matching function for call to ‘sort(std::vector<long unsigned int>::iterator, std::vector<long unsigned int>::iterator, <unresolved overloaded function type>)’
我一定已经正确地完成了所有事情,还有 std::sort
的文档提到我可以将函数作为比较运算符传递给 std::sort
( http://www.cplusplus.com/reference/algorithm/sort/ )
提前感谢所有帮助。
最佳答案
您的方法存在几个问题。第一个也是最明显的一点是您不能将成员函数用作自由函数。为了能够调用 compare
,您需要一个类型为 MyClass
的对象和两个整数。在 std::sort
中,该实现将尝试调用一个只有两个整数参数的 free(非成员)函数。
除此之外,您不能在不显式获取其地址的情况下创建指向成员函数的指针。 std::sort(..., compare);
行不会为成员函数编译。虽然非成员函数会自动衰减到指向该函数的指针,但此处并非如此。
在 C++11 中,您可以采用两种不同的解决方案。最通用的是创建一个捕获 this
参数的 lambda:
std::sort(std::begin(i),std::end(i),
[](int x, int y) { return compare(x,y); }); // or maybe even implement here
另一种方法是将对象和成员函数绑定(bind)到仿函数中:
std::sort(std::begin(i),std::end(i),
std::bind(&MyClass::compare,this,_1,_2));
在最后一种情况下,std::bind
函数将创建一个对象,该对象实现了带有两个参数的 operator()
并将调用成员函数 MyClass::compare
在 this
指向的对象上。
这两种方法的语义略有不同,但在这种情况下,您可以使用任何一种。
关于c++ - 传递类的私有(private)方法作为 std::sort 的比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18273997/