std::map Requirements for Keys (Design Decision)

后端 未结 5 1208
天涯浪人
天涯浪人 2021-02-13 18:24

When I make a std::map, what C++ expects from me is that my_data_type has its own operator<.

5条回答
  •  情歌与酒
    2021-02-13 19:13

    You have a faulty assumption:

    !(a < b) && !(b < a) means that a is neither less than b nor greater than it, so they must be equal.

    It means that they are equivalent, but not necessarily equal. You are free to implement operator< and operator== in such a way that two objects can be equivalent but not equal.

    Why hasn't the C++ designer require operator== to be explicitly defined?

    To simplify the implementation of types that can be used as keys, and to allow you to use a single custom comparator for types without overloaded operators. The only requirement is that you supply a comparator (either operator< or a custom functor) that defines a partial ordering. Your suggestion would require both the extra work of implementing an equality comparison, and the extra restriction of requiring equivalent objects to compare equal.

提交回复
热议问题