Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unordered_map iteration order for the same key

Tags:

c++

c++11

c++14

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
like image 903
Ian Avatar asked Mar 16 '23 19:03

Ian


1 Answers

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.

like image 100
Mike Seymour Avatar answered Mar 27 '23 11:03

Mike Seymour