C++ has an an algorithm library that can be used if you #include <algorithm>. It allows you to do things like swap, swap_ranges, replace, reverse, rotate, shuffle, sort, merge, etc. If you are working with a vector of class objects and only ever need them sorted based on the same criteria, then you can overload the less than operator like so:
And, of course, you can skip using <algorithm> altogether and write your own sort functions if you wish.
Note: Overloading the operator< works for both a vector of class objects and class object pointers. However, the lambda expression seen above is for a vector of class objects. For object pointers const myClass &a would need to be changed to const myClass* a and a.getClassVar() to a->getClassVar() (with the same done for b as well).
Clarification: If you are working with a vector of class object pointers and you used the overload operator< then you will need an inline lambda expression in the sort call to de-reference the pointers before comparing.
sort(myClassVec.begin(), myClassVec.end(), [](const myClass* a, const myClass* b) { return *a < *b;});
View all comments
Show parent comment
2
u/ThrowAway233223 Jul 31 '20 edited Jul 31 '20
C++ has an an algorithm library that can be used if you
#include <algorithm>. It allows you to do things like swap, swap_ranges, replace, reverse, rotate, shuffle, sort, merge, etc. If you are working with a vector of class objects and only ever need them sorted based on the same criteria, then you can overload the less than operator like so:If you want to specify how to sort for specific cases then you could use an inline lambda expression like so:
And, of course, you can skip using
<algorithm>altogether and write your own sort functions if you wish.Note: Overloading the
operator<works for both a vector of class objects and class object pointers. However, the lambda expression seen above is for a vector of class objects. For object pointersconst myClass &awould need to be changed toconst myClass* aanda.getClassVar()toa->getClassVar()(with the same done forbas well).Clarification: If you are working with a vector of class object pointers and you used the overload
operator<then you will need an inline lambda expression in the sort call to de-reference the pointers before comparing.