[英]Custom sort compare function throws compile error
A custom sort function in C++ on VC++ 2012 throws a compile error for the following code. VC ++ 2012上的C ++中的自定义排序函数会为以下代码引发编译错误。
class Segmenter(){
public:
vector<vector<float>> scanned;
void modifyAndSort();
bool sort_fn(const vector<float>&, const vector<float>&);
};
void Segmenter::modifyAndSort(){
// Modify scanned
// ...
sort(scanned.begin(), scanned.end(), sort_fn);
}
bool Segmenter::sort_fn(const vector<float>& x, const vector<float>& y){
return ((x[0]*x[1]) < (y[0]*y[1]));
}
The error thrown is: 引发的错误是:
Error 3 error C3867: 'Segmenter::sort_fn': function call missing argument list; use '&Segmenter::sort_fn' to create a pointer to member
You need: 你需要:
sort(scanned.begin(), scanned.end(), std::bind(&Segmenter::sort_fn, this));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Don't forget to #include <functional>
. 不要忘记
#include <functional>
。
A couple ways other ways to do this. 其他几种方式可以做到这一点。
We can't just pass in a class method without binding the instance as Kerrek SB does in his answer. 我们不能像Kerrek SB在他的回答中那样,在不绑定实例的情况下传递类方法。 A method will have a hidden
this
parameter whether you use it or not. 无论是否使用,方法都会隐藏
this
参数。
In this case it looks like you use it not, so a static method is probably the easiest: 在这种情况下,您似乎没有使用它,因此静态方法可能是最简单的方法:
class Segmenter{
public:
vector<vector<float>> scanned;
void modifyAndSort();
static bool sort_fn(const vector<float>&, const vector<float>&);
};
void Segmenter::modifyAndSort(){
// Modify scanned
// ...
sort(scanned.begin(), scanned.end(), &sort_fn);
// ^ note: we need a pointer to the method.
}
bool Segmenter::sort_fn(const vector<float>& x, const vector<float>& y){
return ((x[0]*x[1]) < (y[0]*y[1]));
}
Slightly more and less complicated at the same time option is everybody's close, personal friend the Lambda Function : 同时,每个人的亲密朋友Lambda Function的选择稍微复杂一些,而后者又稍微复杂一些:
class Segmenter
{
public:
vector<vector<float>> scanned;
void modifyAndSort();
};
void Segmenter::modifyAndSort()
{
// Modify scanned
// ...
sort(scanned.begin(),
scanned.end(),
[](const vector<float>& x, const vector<float>& y)->bool
{
return ((x[0]*x[1]) < (y[0]*y[1]));
});
}
Note: you will need two more Lambdas to get an electric violin solo . 注意:您将需要另外两个Lambda才能获得电子小提琴独奏 。
std::bind() definitely works. std :: bind()绝对有效。
A simple method with just a struct. 一个只有结构的简单方法。
void Segmenter::modifyAndSort(){
// Modify scanned
// ...
sort(scanned.begin(), scanned.end(), Compare());
}
struct Compare {
bool operator()(vector<int> x, vector<int> y) const {
return ((x[0]*x[1]) < (y[0]*y[1]));
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.