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 '<'.
No comments:
Post a Comment