how to output elements in unordered_map with keys in ascending order?

4.8k views Asked by At

I stored some intermediate results in unordered_map. Now when trying to output it, it shows that the keys are in descending order. Is there a way to display it in the other order? How?

3

There are 3 answers

2
Lightness Races in Orbit On

You can't.

An unordered map is just that: unordered.

You cannot make any assumptions about iteration order whatsoever.

This is the trade-off for the increased efficiency of some operations over an unordered map as compared to a normal map. If you want ordering, you'll have to sacrifice those increases.

0
101010 On

You could copy your elements in a std::vector then use std::sort to sort this vector according to your preference ascending/descending and then output it:

std::unordered_map<int, int> um {{2, 3}, {6, 7}, {0, 5}};
std::vector<std::pair<int, int>> sorted_elements(um.begin(), um.end());
std::sort(sorted_elements.begin(), sorted_elements.end());

LIVE DEMO

As for why you can't sort unordered STL containter take a look here

0
Steephen On

If you prefer to keep intermediate data in sorted order, use std::map<key,value> instead std::unordered_map. It will sort on key by default using std::less<> so you will get result in ascending order.

std::unordered_map is an implementation of hash table data structure, so it will arrange the elements internally according to the hash value using by std::unordered_map. But in case std::map it is usually a red black binary tree implementation.