What’s wrong with the following code?
|
|
Answer: my_pair
cannot be used as a key for a STL map because the operator<
violates the rule of strict weak ordering. More specifically, the operator is not antisymmetric. Consider the following:
|
|
Both p1 < p2
and p2 < p1
evaluate to true.
If you use my_pair
as a key into a map you will not get any compiler errors or warnings but you will likely see some bizarre runtime behavior. For example, keys which were successfully insert()
ed may not be able to be found using find()
.
A correct version of operator<
(which places minimal burden on T1
and T2
— they are only required to implement operator<
) is:
|
|