Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use unordered_map and not std::map

Tags:

c++

hashmap

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 ?

like image 572
Guillaume Paris Avatar asked May 30 '11 08:05

Guillaume Paris


People also ask

Should I use map or unordered_map?

map is used to store elements as key,value pairs in sorted order. unordered_map is used to store elements as key,value pairs in non-sorted order.

What is the difference between std::map and std :: unordered_map?

std::map Internally store elements in a balanced BST. Therefore, elements will be stored in sorted order of keys. std::unordered_map store elements using hash table. Therefore, elements will not be stored in any sorted order.

Which is faster std::map or std :: unordered_map?

Therefore, the optimized access with std::map is about 20% faster, but the access time of std::unordered_map about 6 times faster.

Which is faster map or unordered_map C++?

Generally, an unordered_map in C++ is faster than map in C++ because the average time complexity for insertion, deletion, and updation is O(1) while in the case of map, the average time complexity for all the operations is O(log(n)) where n is the number of elements present inside the map.


2 Answers

map

  1. Usually implemented using red-black tree.
  2. Elements are sorted.
  3. Relatively small memory usage (doesn't need additional memory for the hash-table).
  4. Relatively fast lookup: O(log N).

unordered_map

  1. Usually implemented using hash-table.
  2. Elements are not sorted.
  3. Requires additional memory to keep the hash-table.
  4. Fast lookup O(1), but constant time depends on the hash-function which could be relatively slow. Also keep in mind that you could meet with the Birthday problem.
like image 164
Kirill V. Lyadvinsky Avatar answered Sep 21 '22 05:09

Kirill V. Lyadvinsky


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.

like image 43
Macke Avatar answered Sep 21 '22 05:09

Macke