+ 1
Does unordered map also sort elements like map?
Hi I thought that unordered_map does not sort elements based on key value. But it does sort like map as per below code: https://code.sololearn.com/c3a17nlZxIzH If map and unordered_map does sorting, what is difference between two?
1 Respuesta
+ 1
From the documentation:
"Unordered map is an associative container that contains key-value pairs with unique keys. Search, insertion, and removal of elements have average constant-time complexity.
Internally, the elements are not sorted in any particular order, but organized into buckets. Which bucket an element is placed into depends entirely on the hash of its key. This allows fast access to individual elements, since once the hash is computed, it refers to the exact bucket the element is placed into."
https://en.cppreference.com/w/cpp/container/unordered_map
If you add these lines you'll see that it does not print them in a sorted order anymore:
obj.insert(pair<int,string>(3,"A"));
obj.insert(pair<int,string>(4,"B"));
obj.insert(pair<int,string>(5,"C"));
obj.insert(pair<int,string>(6,"D"));
obj.insert(pair<int,string>(7,"E"));