Saturday, April 26, 2008

Using '<' Operator to Compare

In C++ Standard Template Library (STL), some algorithms such as sorting, need to compare two elements. STL uses less operator '<' to accomplish the purpose. When you need to apply those algorithms to your custom data structure, you must overload less operator '<'. But sometimes, you need '!=', '>', etc. How to use '<' to implement all the operators?

For example, if you have a<b, then:
  • if you need a>b, just write 'b<a';
  • if you need a!=b, use 'a<b||b<a';
  • if you need a==b, use '!(a<b||b<a)';
  • if you need a>=b, use '!(a<b)';
  • the last, if you need a<=b, use '!(b<a)'.
So, all comparison operators can be implemented by less operator '<'.

1 comment:

amit said...

Nice tutorial....thanks for this post.....
Please visit this link for learn more script.