I'm curious about this behaviour. I found that assigning an unordered_map changes the internal order of the unordered map, without any insertion/deletion:
unordered_map<int, string> m1;
unordered_map<int, string> m2;
unordered_map<int, string> m3;
m1[2] = "john";
m1[4] = "sarah";
m1[1] = "mark";
m2 = m1;
m3 = m2;
for(auto it = m1.begin(); it != m1.end(); ++it) {
cout << it->second << " ";
}
cout << endl;
for(auto it = m2.begin(); it != m2.end(); ++it) {
cout << it->second << " ";
}
cout << endl;
for(auto it = m3.begin(); it != m3.end(); ++it) {
cout << it->second << " ";
}
cout << endl;
outputs:
mark sarah john
john sarah mark
mark sarah john
I know that there isn't any specific order maintained on an unordered_map due to the fact that internally is a hash table, so an element insertion can end anywhere and a re-hash will mix it all.
However, here the order is changing just after an assignment. I expected the order to be the same, as I thought it would just copy the underlying storage.
The first explanation I thought was that maybe unordered_map is taking advantage of the copy to re-hash the new map into a more optimal arrangement. However, I tried to repeat an assignment on a new map (m3) from m2 and the order of m2 is not preserved in m3.
Why does assigning the map change the order?
My compiler is Apple LLVM version 8.1.0 (clang-802.0.42)