1

Consider implementing operator< for the following class:

struct foo {
  int a, b;
};

Probably the most common way is something like the element-wise lexicographic compare, like so:

bool operator<(foo lhs, foo rhs) {
  return lhs.a < rhs.a || (lhs.a == rhs.a && lhs.b < rhs.b);
}

I've written that enough times, and made a type enough times that I'm wondering if there is something built in to std:: that will do it for me, hopefully with less boilerplate and reasonable code generation.

Now the above for two elements isn't that bad, but the terms multiply as you add more members.

BeeOnRope
  • 60,350
  • 16
  • 207
  • 386
  • 2
    There are some fun tricks with `std::tie`. I'll see if I can dig up one of them. – user4581301 Oct 23 '19 at 02:23
  • 1
    Here's one: [operator< comparing multiple fields](https://stackoverflow.com/questions/11312448/operator-comparing-multiple-fields) – user4581301 Oct 23 '19 at 02:25
  • @user4581301 - nice, looks like the [codegen is just as good](https://godbolt.org/z/YMCy50) at least for these simple cases. – BeeOnRope Oct 23 '19 at 02:29
  • And soon (C++20) [spaceship operator](https://en.cppreference.com/w/cpp/language/default_comparisons) to the rescue. – Jarod42 Oct 23 '19 at 08:52

1 Answers1

0

You can use pair<int, int> instead of struct foo.

As pair<type,type> is builtin in std:: it has comparator for all builtin data type. So you don't need any extra operator overloading or a custom comparator. Even it works for strings. std:: compare two pair<type, type> based on the first element of the pair. If it's a tie then the tie is broken based on the second element.

For example-

  • pair<int,int> a = make_pair(5,10) //declare using make_pair()
  • pair<int,int> b = {5,7} //different way of declaring pair.
  • pair<int,int> c = pair<int,int>(7,7) //declare using constructor

Now a < b == false, b < c == true and a < c == true

So in this way, you can use pair<type, type> instead of struct foo. You can replace 'type' using any data type like float, long long, char, string, pair, vector, set, map, complex etc.

Tanmoy Datta
  • 1,604
  • 1
  • 17
  • 15