say I have a class "Information" and it stores the Name and Age of people in a vector.
so...
class Information {
private:
int age;
string name;
//etc, etc...
};
How would I sort the vector in either ascending/descending order with respect to age?
I believe you use something like this.
sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());
listOfPeople would be the vector.
Any help would be greatly appreciated.
If you want to sort them in non-descending order by age, one way to do it is to define a functor for comparison:
class CompareInformations {
public:
// after making CompareInformations a friend class to Information...
operator(const Information& rhs, const Information& lhs) {
return rhs.age < lhs.age;
}
};
And then do your sort:
sort(listOfPeople.begin(), listOfPeople.end(), CompareInformations());
You could also overload operator<
for your class, and do without the comparison object:
// inside your class
bool operator <(const Information& rhs) {
return age < rhs.age;
}
Then sort it:
sort(listOfPeople.begin(), listOfPeople.end());
The above examples assume you want to sort in non-descending (almost ascending, but not quite) order. To do non-ascending order, just change all occurrences of <
to >
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With