Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do values with same hash go in same bucket of std::unordered_map?

Tags:

c++

c++11

stl

If two keys for a std::unordered_map have the same hash value, is it guaranteed by the standard that they will go into the same bucket? We are assuming that the keys are not equal according to the template equality predicate, they only have the same hash value.

Bonus question: If same hash does not imply same bucket, then what is the purpose of being able to traverse buckets individually?

like image 599
Bjarke H. Roune Avatar asked Oct 15 '12 18:10

Bjarke H. Roune


People also ask

Can we store duplicate values in unordered_map?

We have discussed unordered_map in our previous post, but there is a limitation, we can not store duplicates in unordered_map, that is if we have a key-value pair already in our unordered_multimap and another pair is inserted, then both will be there whereas in case of unordered_map the previous value corresponding to ...

Are elements sorted in unordered_map?

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

How are elements stored in unordered_map?

unordered_map is an associated container that stores elements formed by the combination of a key value and a mapped value. The key value is used to uniquely identify the element and the mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defined.

Which hashing is used in unordered_map?

The unordered_map::hash_function() is a built in function in C++ STL which is used to get the hash function. This hash function is a unary function which takes a single argument only and returns a unique value of type size_t based on it.


1 Answers

Objects with the same hash are put into the same bucket by unordered associative containers. Consequently, two equal objects must have the same hash.

23.2.5 paragraph 8:

The elements of an unordered associative container are organized into buckets. Keys with the same hash code appear in the same bucket.

Bonus question: Why might you want to traverse buckets individually?

Bonus answer: Because you want to process the container's contents in parallel. The bucket iterators are independent of each other, so each thread can process a bucket without co-ordination (provided no new entries are added to the container). And the buckets should be roughly the same size, so they provide a convenient parallelisation quantum.

like image 159
rici Avatar answered Sep 22 '22 01:09

rici