Suppose a class has multiple members relevant to the objects' order, e.g., A { T1 x; T2 y; };. The standard implementation of operator< I know is
bool A::operator<(const A& a) { return x < a.x || (x == a.x && y < a.y); } But that looks horribly inefficient to me, especially when T1 is std::vector. (It's even inefficient to read and maintain when there are more members.)
Is there a "standard" C++-way of comparing things efficiently? Or does everyone go her own way like so:
enum Cmp = {LESS,EQUAL,GREATER} Cmp A::CompareTo(const A& a) { const Cmp c1 = x.CompareTo(a.x); if (c1 != EQUAL) return c1; const Cmp c2 = y.CompareTo(a.y); return c2; } And for std::vector one would perhaps use std::mismatch to implement such a CompareTo?
(I'm sure that's not a new question, but operator< is a bad search term.)
operator <is actually a relevant bottleneck before you go optimizing it; the best way to implement it is the way that is clearest and easily maintainable as possible.operator<should respect. (2) The "standard" way to implementoperator<isn't even very maintainable, I think, compared to the second solution. (You disagree?) In general I of course agree to first profile and then optimize.