A flexible lexicographical comparator for C++ structs--Björn Fahller

An interesting article:

A flexible lexicographical comparator for C++ structs

by Björn Fahller

From the article:

We've all hand crafted comparison operators for structs with many members, and we've all cursed the tedium. It's all right for equality comparison, but lexicographical ordering relations is a different story when there are more than two members.

Hopefully all C++ developers have by now learned about the std::tie()-idiom.

struct S
{
  int a;
  int b;
  int c;
};

bool operator<(const S& lh, const S& rh)
{
  return std::tie(lh.a, lh.b, lh.c)
       < std::tie(rh.a, rh.b, rh.c);
}

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.