Wednesday, October 30, 2013

How to write a compare function


std::map , std::set and std::sort may require that you write a custom compare function, so the elements can be sorted.
Writing the compare function correctly is critical, as a mistake can make your program crash.
There is a typical pattern you can follow, to write a compare function.



Assuming you have some composite struct X:

struct X {
    int first;   
    int second;    
    double third;
};

you can compose the compare function in the following manner
bool compare( const X& lhs, const X& rhs )
{
  if (lhs.first < rhs.first) return true;
  if (rhs.first < lhs.first) return false;

  if (lhs.second < rhs.second) return true;
  if (rhs.second < lhs.second) return false;

  return lhs.third < rhs.third;
}

map<X, int, bool(*)(const X&,const X&) > x_values(compare);
 

Needless to say, that for possible increase in speed, a function object would be more appropriate to use, as it increases the possibility of getting inlined. Here's the equivalent functor:

struct Compare {
  bool operator() ( const X& lhs, const X& rhs )
  {
    if (lhs.first < rhs.first) return true;
    if (rhs.first < lhs.first) return false;

    if (lhs.second < rhs.second) return true;
    if (rhs.second < lhs.second) return false;

    return lhs.third < rhs.third;
  }
};

map<X, int, Compare>  x_values;
  

You can also look at different ways to do this here.

No comments:

Post a Comment