Skip to main content
edited tags
Link
Jason C
  • 40.6k
  • 16
  • 136
  • 201
Source Link
chs
  • 662
  • 4
  • 17

Efficient operator< with multiple members

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.)