Choosing between std::map and std::unordered_map
As already mentioned, map
allows to iterate over the elements in a sorted way, but unordered_map
does not. This is very important in many situations, for example displaying a collection (e.g. address book). This also manifests in other indirect ways like: (1) Start iterating from the iterator returned by find()
, or (2) existence of member functions like lower_bound()
.
Also, I think there is some difference in the worst case search complexity.
For
map
, it is O( lg N )For
unordered_map
, it is O( N ) [This may happen when the hash function is not good leading to too many hash collisions.]
The same is applicable for worst case deletion complexity.
In addition to the answers above you should also note that just because unordered_map
is constant speed (O(1)
) doesn't mean that it's faster than map
(of order log(N)
). The constant may be bigger than log(N)
especially since N
is limited by 232 (or 264).
So in addition to the other answers (map
maintains order and hash functions may be difficult) it may be that map
is more performant.
For example in a program I ran for a blog post I saw that for VS10 std::unordered_map
was slower than std::map
(although boost::unordered_map
was faster than both).
Note 3rd through 5th bars.
This is due to Google's Chandler Carruth in his CppCon 2014 lecture
std::map
is (considered by many to be) not useful for performance-oriented work: If you want O(1)-amortized access, use a proper associative array (or for lack of one, std::unorderded_map
); if you want sorted sequential access, use something based on a vector.
Also, std::map
is a balanced tree; and you have to traverse it, or re-balance it, incredibly often. These are cache-killer and cache-apocalypse operations respectively... so just say NO to std::map
.
You might be interested in this SO question on efficient hash map implementations.
(PS - std::unordered_map
is cache-unfriendly because it uses linked lists as buckets.)