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 ?
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.
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.
Therefore, the optimized access with std::map is about 20% faster, but the access time of std::unordered_map about 6 times faster.
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.
map
unordered_map
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With