How can I sort an unordered_map
by key? I need to print an unordered_map
sorted by key.
An unordered_map is a hash container, that is, the keys are hashed. Inside of the container, they don't have the same representation as on the outside. Even the name implies that you can't sort it.
By default, a Map in C++ is sorted in increasing order based on its key.
If you use more modern Studio like 2017 - then unordered_map much faster than ordered map.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With