Why use std::less as the default functor to compare keys in std::map and std::set?

前端 未结 2 1543
夕颜
夕颜 2020-12-16 09:40

I am wondering why std::map and std::set use std::less as the default functor to compare keys. Why not use a functor that works simila

2条回答
  •  猫巷女王i
    2020-12-16 10:12

    Tree based containers only require Strict Weak Total Ordering.

    See https://www.sgi.com/tech/stl/StrictWeakOrdering.html

    1. write access

      The insertion point for maps and sets is purely determined by a single binary search, e.g. lower_bound or upper_bound. The runtime complexity of binary search is O(log n)

    2. read access

      The same applies to searching: the search is vastly more efficient than a linear equality scan, precisely because most elements do not need to be compared. The trick is that the containers are ordered.


    The upshot is that the equality information need not be present. Just, that items can have equivalent ordering.

    In practice this just just means fewer constraints on your element types, less work to implement the requirements and optimal performance in common usage scenarios. There will always be trade-offs. (E.g. for large collections, hash-tables (unordered sets and maps) are often more efficient. Note that these do require equatable elements, and they employ a hashing scheme for fast lookup)

提交回复
热议问题