Could anybody explain me what is the difference between overload == and <?
For example, if I use a map:
map<Type, int> a();
friend bool operator<(const Type& lhs, const Type& rhs);
friend bool operator==(const Type& lhs, const Type& rhs);
And I implement both operators, when I call:
a.find(value);
The operator function of == is being called? I think not. I debugged and saw that < is called, but why? What should be the behavior of the operator function of <?
I come from Java where the method equals is called and is pretty simple to understand the behavior.
Thanks.
operator==overloads the==operator (and no other);operator<overloads the
<operator (and no other).std::mapis defined to usestd::less(and onlystd::less) bydefault, and
std::lessis defined to use<by default. In general,however, I would recommend not overloading
operator<unlessordered 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 shoulddefine 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 tostd::map) requires thekeys to be Comparable, however, which in turn requires a
comparefunction, which returns a value
<,==or>0, depending on whetherthisis<,==or>than other. I’ll admit that I find this alittle bit more logical, but the difference is very, very small. (The
rationale behind the C++ decision is that build-in types like
intordoublecan be used as keys. In Java, you’ld have to box them.)