Reputation: 10539
I'm wondering in which case I should use unordered_map instead of std::map.
I have to use unorderd_map each time I don't pay attention of order of element in the map ?
Upvotes: 16
Views: 12387
Reputation: 99535
map
unordered_map
Upvotes: 23
Reputation: 146910
unordered_map
is O(1) but quite high constant overhead for lookup, insertion, and deletion. map
is O(log(n)), so pick the complexity that best suits your needs. In addition, not all keys can be placed into both kinds of map.
Upvotes: 0
Reputation: 25680
Compare hash table (undorded_map
) vs. binary tree (map
), remember your CS classes and adjust accordingly.
The hash map usually has O(1) on lookups, the map has O(logN). It can be a real difference if you need many fast lookups.
The map keeps the order of the elements, which is also useful sometimes.
Upvotes: 1
Reputation: 59101
The reason you'd choose one over the other is performance. Otherwise they'd only have created std::map
, since it does more for you :)
Use std::map
when you need elements to automatically be sorted. Use std::unordered_map
other times.
See the SGI STL Complexity Specifications rationale.
Upvotes: 0
Reputation: 206508
map
allows to iterate over the elements in a sorted way, but unordered_map
does not.
So use the std::map
when you need to iterate across items in the map in sorted order.
Upvotes: 0