[英]sort on a class member got the error unresolved overloaded function type
class S {
public:
vector <int> ia;
int rank;
bool cmp(S const &s1, S const &s2) {
return (s1.rank > s2.rank);
}
void sort_on_rank() {
sort(ia.begin(), ia.end(), cmp);
}
};
This piece of code is trying to sort the vector on rank, but doesn't compile because of following error, 这段代码试图对向量进行排序,但是由于以下错误而无法编译,
[Error] no matching function for call to 'sort(std::vector::iterator, std::vector::iterator, )' [错误]没有匹配的函数调用'sort(std :: vector :: iterator,std :: vector :: iterator,)'
Please help me on this and tell where is the problem. 请对此提供帮助,并告诉问题出在哪里。
From your program it seems you want to sort objects of S
classes. 从您的程序看来,您想要对
S
类的对象进行排序。 In that case your vector should be like this : std::vector<S>
. 在这种情况下,您的向量应该像这样:
std::vector<S>
。
Your cmp
is a non-static member function of class S
and hence std::sort
cannot work with it. 您的
cmp
是类S
的非静态成员函数,因此std::sort
无法使用它。 (Think about how will you use the function). (考虑如何使用该功能)。
You can either overload <
operator for your class or pass a stand-alone/static member function or you can use C++11 lambda expression. 您可以为类重载
<
运算符,也可以传递独立/静态成员函数,也可以使用C ++ 11 lambda表达式。
Thus your class becomes: 因此,您的课程变为:
class S {
public:
vector<S> ia;
int rank;
void sort_on_rank() {
sort(ia.begin(), ia.end(),
[] (S const &s1, S const &s2) {
return (s1.rank > s2.rank);
});
}
};
However if you want to merely sort vector containing int
in descending order, just call std::sort
with a C++11 lambda that returns lhs > rhs
. 但是,如果您只想按降序对包含
int
向量进行排序,只需使用返回lhs > rhs
的C ++ 11 lambda调用std::sort
。
std::sort(ia.begin(), ia.end(), [](int x, int y) { return x > y; });
您的S::cmp()
接受S
,但S::ia
的值类型为int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.