How to choose between map and unordered_map?

前端 未结 4 1726
一个人的身影
一个人的身影 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:52

                           | map              | unordered_map
    ---------------------------------------------------------
    element ordering       | strict weak      | n/a 
                           |                  |
    common implementation  | balanced tree    | hash table
                           | or red-black tree|  
                           |                  |
    search time            | log(n)           | O(1) if there are no hash collisions
                           |                  | Up to O(n) if there are hash collisions 
                           |                  | O(n) when hash is the same for any key
                           |                  |     
    Insertion time         | log(n)+rebalance | Same as search
                           |                  | 
    Deletion time          | log(n)+rebalance | Same as search
                           |                  | 
    needs comparators      | only operator <  | only operator ==
                           |                  |
    needs hash function    | no               | yes
                           |                  |
    common use case        | when good hash is| In most other cases. 
                           | not possible or  | 
                           | too slow. Or when|
                           | order is required| 
    

提交回复
热议问题