如何使用自定义比较器对数组排序? [英] How can I sort an array using a custom comparator?
问题描述
当我从下面的代码调用 build
函数时,出现以下编译错误:
When I call my build
function from my code below, I get the following compile errors:
error C3867: 'SuffixArray::cmp': function call missing argument list; use '&SuffixArray::cmp' to create a pointer to member
error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided
这是我的代码:
class A{
private:
std::string text;
std::vector<int> array;
bool cmp(int a, int b) {
return std::lexicographical_compare(text.begin() + a, text.end(),
text.begin() + b, text.end());
}
void build(const std::string &str, std::vector<int> &vec) {
// Some vector values actions.
std::sort(vec.begin(), vec.end(), cmp);
}
};
这是怎么了?我正在使用Visual C ++编译器.
What's wrong here? I'm using the Visual C++ compiler.
推荐答案
您的比较函数 A :: cmp
是 A
的非静态成员.因此,它需要三个参数:除了显式声明的两个参数之外,它还需要一个指向 A
的指针,以使其成为隐式可用的 this
.它也具有与普通函数指针不同的类型: bool(A ::)(int,int)
衰减为 bool(A :: *)(int,int)
>通过值传递时.
Your comparison function A::cmp
is a non-static member of A
. Thus, it takes three arguments: in addition to the two arguments explicitly declared, it also takes a pointer to A
to become the implicitly available this
. It also has a different type than normal function pointers: bool (A::)(int, int)
which decays into bool (A::*)(int, int)
when being passed by value.
您可以将函数 std :: bind()
定位到合适的对象,但是:
You could std::bind()
your function to a suitable object, however:
std::sort(vec.begin(), vec.end(),
std::bind(&A::cmp, this, std::placeholders::_1, std::placeholders::_2));
这篇关于如何使用自定义比较器对数组排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!