C++ overloading operators difference between == and <

前端 未结 6 1310
花落未央
花落未央 2021-01-21 17:01

Could anybody explain me what is the difference between overload == and <?

For example, if I use a map:

map         


        
6条回答
  •  无人共我
    2021-01-21 17:07

    operator== overloads the == operator (and no other); operator< overloads the < operator (and no other).

    std::map is defined to use std::less (and only std::less) by default, and std::less is defined to use < by default. In general, however, I would recommend not overloading operator< unless ordered comparison makes sense for your class, in which case, you should overload all six comparison operators, in a coherent fashion. Otherwise, you can specify a comparison functional type as an additional template argument to std::map; the comparison functional object should define a strict weak ordering relationship. If the type is designed to be used as a key, but the ordering is still purely arbitrary, you might specialize std::less.

    As for Java, without operator overloading, it obviously can't use <; by default, SortedMap (the Java equivalent to std::map) requires the keys to be Comparable, however, which in turn requires a compare function, which returns a value <, == or > 0, depending on whether this is <, == or > than other. I'll admit that I find this a little bit more logical, but the difference is very, very small. (The rationale behind the C++ decision is that build-in types like int or double can be used as keys. In Java, you'ld have to box them.)

提交回复
热议问题