Reputation: 43
When looping over an std::unordered_map
, STL makes no guarantees on which specific element order is considered.
My question is about the order of the elements with the same key, I tried it with different compilers and I always receive one after the other if they have same key (example below). I searched it but I couldn't find. Is it mentioned somewhere in standards or it is implementation dependent?
unordered_multimap<int, int> umap;
umap.insert({30, 9});
umap.insert({10, 1});
umap.insert({20, 5});
umap.insert({30, 8});
umap.insert({20, 4});
umap.insert({10, 2});
for (auto p : umap)
cout << p.first << " " << p.second << endl;
outputs
30 8
30 9
20 4
20 5
10 1
10 2
Upvotes: 4
Views: 1119
Reputation: 254461
Yes, it's mentioned in C++11 23.2.5/6:
In containers that support equivalent keys, elements with equivalent keys are adjacent to each other in the iteration order of the container.
Upvotes: 7