### How sort a unordered_map in alphabetical order?

Hi, i want sort this unordered_map in alphabetical order with the function sort of the library algorithm using vectors. Look the my code! Help me!

#include <iostream>
#include <algorithm>
#include <string>
#include <unordered_map>

using namespace std;

int main()

{
unordered_map<string, int> h;

h["GG"] = 5;
h["HF"] = 1;
h["GL"] = 3;
h["SS"] = 6;

unordered_map<string, int>::iterator it;

for(it = h.begin(); it != h.end(); it++)
cout <<(*it).first << endl;

return 0;
}
Loop through the unordered_map and add each key to the vector and then sort the vector after the loop. Or you could simply use std::map instead of std::unordered_map and it would always be sorted automatically.
Last edited on
 Hi, i want sort this unordered_map in alphabetical order with the function sort of the library algorithm using vectors. Look the my code! Help me!

Sort requires a container to have a random-access-operator, unordered map does not fulfill that condition so you can't sort it with sort.

You could, like Peter87 said, use std::map instead of std::unordered_map, then the keys will allways be sorted.
The standard sort condition is allways less-than, so the smallest element will be at the beginning.
If you want to have it sorted differently use the 3rd template parameter to give it a compare predicate, for example a function-object from the c++ standard.
The c++ standard provides a list of function-objects for comparison: http://www.cplusplus.com/reference/functional/

 ``123456789101112131415161718192021222324`` ``````#include #include #include #include #include using namespace std; int main() { map> h; h["GG"] = 5; h["HF"] = 1; h["GL"] = 3; h["SS"] = 6; map::iterator it; for(it = h.begin(); it != h.end(); it++) cout <<(*it).first << endl; return 0; }``````
Peter87, can you show me in code this that write.... I'm with difficults!!!
There is an example in the previous post so I'm not sure what you are asking Ozzy69. Unordered containers are named that way for a reason. They are not supposed to be sorted. They are typically implemented using hashing so that accessing and storing items is faster.
Topic archived. No new replies allowed.