Search code examples
c++lexicographic

What's the simplest way of defining lexicographic comparison for elements of a class?


If I have a class that I want to be able to sort (ie support a less-than concept), and it has several data items such that I need to do lexicographic ordering then I need something like this:

struct MyData {
  string surname;
  string forename;

  bool operator<(const MyData& other) const {
    return surname < other.surname || (surname==other.surname && forename < other.forename); }
};

This becomes pretty unmanageable for anything with more than 2 data members. Are there any simpler ways of achieving it? The data members may be any Comparable class.


Solution

  • With the advent of C++11 there's a new and concise way to achieve this using std::tie:

    bool operator<(const MyData& other) const {
      return std::tie(surname, forename) < std::tie(other.surname, other.forename);
    }