Iterating over unordered_map C++

Sonu Patidar picture Sonu Patidar · Jun 15, 2018 · Viewed 38.8k times · Source

Is it true that keys inserted in a particular order in an unordered_map, will come in the same order while iterating over the map using iterator?

Like for example: if we insert (4,3), (2, 5), (6, 7) in B. And iterate like:

for(auto it=B.begin();it!=B.end();it++) {
    cout<<(it->first); 
}

will it give us 4, 2, 6 or keys may come in any order?

Answer

Aimery picture Aimery · Jun 15, 2018

From the cplusplus.com page about the begin member function of unordered_map (link):

Notice that an unordered_map object makes no guarantees on which specific element is considered its first element.

So no, there is no guarantee the elements will be iterated over in the order they were inserted.

FYI, you can iterate over an unordered_map more simply:

for (auto& it: B) {
    // Do stuff
    cout << it.first;
}