问题
Let
class Record {
public:
Record();
private:
string id;
double score;
};
Somewhere we define a vector of Record objects, i.e.,
vector<Record> records(N);
// Initialize records somehow
I would like to sort records based on score
(in descending order) keeping track of the other member variables of Record
(in this case just the score
, but in general whatever else).
回答1:
You can implement the comparison operators.
bool Record::operator<(const Record& rhs) {
return score < rhs.score;
}
bool Record::operator<=(const Record& rhs) {
return score <= rhs.score;
}
Note, if you define <
and <=
, you should also probably define the other comparison operators >
, >=
, ==
, and !=
. You should also enforce a strict weak ordering (e.g. a < b
, b < c
implies a < c
).
Then to sort descending, you could use the following...
std::sort(records.begin(), records.end(),
[] (const Record& lhs, const Record& rhs) -> bool { return lhs > rhs; });
回答2:
To sort a vector of objects
You could overload a comparison operator >1 for your class, which will look something like:
bool operator> (const Record& r1, const Record& r2) {
return r1.score > r2.score;
}
or as a member function:
bool Record::operator> (const Record& r) {
return score > r.score;
}
which will be implicitly substituted as a third parameter in:
std::sort(records.begin(), records.end(), overloaded_comparison_operator)
You could also use a lambda function directly in sort
:
std::sort(records.begin(), records.end(), [](const Record & r1,const Record & r2) -> bool {
return r1.score > r2.score; });
1. You could use any of the comparison operators you find useful in your case. Bear in mind operator <
will sort in ascending, while operator >
in descending order.
来源:https://stackoverflow.com/questions/34385586/sort-vector-of-class-objects-based-on-some-member-variable