std::map Requirements for Keys (Design Decision)
-
11-11-2019 - |
質問
When I make a std::map<my_data_type, mapped_value>
, what C++ expects from me is that my_data_type
has its own operator<
.
struct my_data_type
{
my_data_type(int i) : my_i(i) { }
bool operator<(const my_data_type& other) const { return my_i < other.my_i; }
int my_i;
};
The reason is that you can derive operator>
and operator==
from operator<
. b < a implies a > b, so there's operator>
. !(a < b) && !(b < a) means that a is neither less than b nor greater than it, so they must be equal.
The question is: Why hasn't the C++ designer require operator==
to be explicitly defined? Obviously, operator==
is inevitable for std::map::find()
and for removing duplicates from the std::map
. Why implement 5 operations and call a method twice in order not to compel me to explicitly implement operator==
?
正しい解決策はありません
所属していません StackOverflow