There's three ways to do this:
You could 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 according to b
, you're out of luck.
You could also specialize std::less
for your type. That makes std::sort
working (and other things, like using the type as a key in a map) without hijacking operator<
for this meaning. It does, however, still hijack a general-purpose comparison syntax for a
, while you might, at other places in your code, compare your type according to b
.
Or you could write your own comparator like this:
struct compare_by_a {
bool operator()(const MyType& lhs, const MyType& rhs) const
{return lhs.a<rhs.a;}
};
(Note: The const
after the operator isn't strictly necessary. I still consider it good style, though.) This leaves the general-purpose means of comparison undefined; so if some code wants to use them without you being aware, the compile emits an eror and makes you aware of it. You can use this or other comparators selectively and explicitly where ever you need comparison.