C++ overloading operators difference between == and <

前端 未结 6 1307
花落未央
花落未央 2021-01-21 17:01

Could anybody explain me what is the difference between overload == and <?

For example, if I use a map:

map         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-21 17:10

    The requirements that the C++ standard places on std::map mean that it is implemented as a self-balancing binary search tree. This means that some kind of ordering comparison between elements must be available. In the case of std::map, the requirement is a strict weak ordering, and the default is a less-than comparison. This is all that is required to arrange elements in a binary tree, and the equality condition is met when one element (call it A) is not less than another one (call it B), and the converse is also true, i.e. B is not less than A. An equality comparison could have been used, but this would open some scope for inconsistency. If you look at hash tables, such as std::unordered_map, you will find that an equality comparison is indeed required, although this is only to resolve collisions.

提交回复
热议问题