跳到主要內容

Tips: Lexicographical Comparable Type in C++

PST: Lexicographical Comparable Type in C++

It has been years since last update to this blog. It should be good to write some small (for happily copy’n paste :-) tips for re-familiar writing.

Lexicographical comparing a aggregated type in C++

struct Version {
 int major;
 int minor;
 int patch;
 friend bool operator < (const Version& lhs, const Version& rhs) {
  if (lhs.major < rhs.major)
   return true;
  if (lhs.minor < rhs.minor)
   return true;
  return lhs.patch < rhs.patch;
 }
};

Nothing wrong with above code. However

#include <tuple>
using Version = std::tuple<int, int, int>;

is sometimes sufficient.

Pro:

  • No need to write all comparison operators

Con:

  • Not that obvious accessing method, e.g. get<0>(var)

– Written with StackEdit.

留言