Implementing operator<() for strict weak ordering

Overload113Cover
The latest edition of Overload Magazine (a publication by the ACCU) includes a recipe for implementing operator<, as is often required when you want store some class in an STL associative container.

bool operator<( const T& rhs ) const
{
if ( a != rhs.a ) return a < rhs.a;
if ( b != rhs.b) return b < rhs.b;
...
return false;
}

This assumes that operator!= exists on that class and in my view muddies the waters between equivalence (the property you test in a std::set or std::map with operator<) and equality (the test in std::vector or std::list with operator==). Of course, if operator== exists, you can easily amend the recipe accordingly, but again neither operator== nor operator!= have default implementations so may not be provided.

Where necessary, you can fall back onto this more verbose recipe:

bool operator <(const T& rhs) const
{
  if ( a < rhs.a )
    return true;
  else if (rhs.a < a)
    return false;

  if ( b < rhs.b)
    return true;
  else if (rhs.b < b)
    return false;

  // repeat for all child elements c, d, e etc
  return false;
}

Leave a comment

Filed under C++ Code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s