Reputation: 1293
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, )'
Please help me on this and tell where is the problem.
Upvotes: 0
Views: 2172
Reputation: 3295
From your program it seems you want to sort objects of S
classes. In that case your vector should be like this : std::vector<S>
.
Your cmp
is a non-static member function of class S
and hence std::sort
cannot work with it. (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.
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
.
std::sort(ia.begin(), ia.end(), [](int x, int y) { return x > y; });
Upvotes: 4
Reputation: 746
Your S::cmp()
takes S
, but S::ia
's value type is int
.
Upvotes: 1