Also, in std::unordered_multimap
, does it presence means all elements with same key will always come together while iterating unordered_multimap
with a iterator?
In general, the order, in which elements stored in a std::unordered_multimap
are obtained while traversing it, is actually not defined. However, note that std::unordered_multimap
s are usually implemented as hash tables. By analysing such an implementation you will realize that the ordering is not going to be as "undefined" as someone might initially think.
At element insertion (or hash table rehashing), the value resulting of applying the hash function to an element's key is used to select the bucket where that element is going to be stored. Two elements with equal keys will result in the same hash value, therefore they will be stored in the same bucket, so they come togetherX while iterating an std::unordered_multimap
.
XNote that even two elements with different keys might also result in the same hash value (i.e., a collision). However, std::unordered_multimap
can handle these cases by comparing the keys against equality, and therefore still group elements with equal keys together.