There are three ways to do this:
You can overload operator< for your class:
bool operator<(const MyType& lhs, const MyType& rhs) {return lhs.a<rhs.a;}
This has the disadvantage that if you ever want to sort them by b , you're out of luck.
You can also specialize std::less for your type. This does the work of std::sort (and other things, such as using the type as the key on the map) without capturing operator< for this value. However, it still captures the general-purpose comparison syntax for a , while elsewhere in your code you can compare your type according to b .
Or you could write your own comparator as follows:
struct compare_by_a { bool operator()(const MyType& lhs, const MyType& rhs) const {return lhs.a<rhs.a;} };
(Note: const after the statement is not strictly necessary. However, I consider it a good style). This leaves the average means of comparison undefined; therefore, if some code wants to use them without your knowledge, the compiler emits an error and informs you about it. You can use this or other comparators selectively and explicitly where you need the comparison.
source share