Could anybody explain me what is the difference between overload ==
and <
?
For example, if I use a map:
map
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.)