How to choose between map and unordered_map?

前端 未结 4 1711
一个人的身影
一个人的身影 2020-11-29 16:24

Suppose I wanted to map data with a string as the key. What container should I have chosen, map or unordered_map? unordered_map takes

4条回答
  •  [愿得一人]
    2020-11-29 16:53

    What container should I have chosen, map or unordered_map? unordered_map takes up more memory so let's suppose memory isn't an issue, and the concern is speed.

    Profile and then decide. unordered_map is generally faster, but it varies per case.

    In what cases would it get to O(n)?

    When the hashing isn't good and a bunch of elements are being assigned to the same bins.

    When does a map get more time efficient than unordered_map? Does it happaen when n is small?

    Probably not, but profile it if you really care. Having a container with a small size be the bottleneck of your program seems extremely unlikely. Anyway, a simple vector with linear search may be faster for such cases.


    The most important thing when deciding is the requirements of ordering and lack of iterator invalidation. If you need either, you pretty much have to use map. Otherwise, unordered_map.

提交回复
热议问题