c++ - Defining operator< for a struct -
i use small structs keys in maps, , have define operator< them.  usually, ends looking this:
struct mystruct {     a;     b b;     c c;      bool operator<(const mystruct& rhs) const     {         if (a < rhs.a)         {            return true;         }         else if (a == rhs.a)         {             if (b < rhs.b)             {                 return true;             }             else if (b == rhs.b)             {                 return c < rhs.c;             }         }          return false;     } }; this seems awfully verbose , error-prone.  there better way, or easy way automate definition of operator< struct or class?
i know people use memcmp(this, &rhs, sizeof(mystruct)) < 0, may not work correctly if there padding bytes between members, or if there char string arrays may contain garbage after null terminators.
this quite old question , consequence answers here obsolete. c++11 allows more elegant , efficient solution:
bool operator <(const mystruct& x, const mystruct& y) {     return std::tie(x.a, x.b, x.c) < std::tie(y.a, y.b, y.c); } why better using boost::make_tuple? because make_tuple create copies of data members, can costly. std::tie, contrast, create thin wrapper of references (which compiler optimise away entirely).
in fact, above code should considered idiomatic solution implementing lexicographical compare structures several data members.
Comments
Post a Comment