Sorting std::unordered_map by key

softwarematter picture softwarematter · Jun 2, 2011 · Viewed 31.2k times · Source

How can I sort an unordered_map by key? I need to print an unordered_map sorted by key.

Answer

ronag picture ronag · Jun 2, 2011
std::unordered_map<int, int> unordered;

std::map<int, int> ordered(unordered.begin(), unordered.end());
for(auto it = ordered.begin(); it != ordered.end(); ++it)
     std::cout << it->second;