How sort a unordered_map in alphabetical order?

May 7, 2015 at 5:48am
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;
}
May 7, 2015 at 6:49am
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 May 7, 2015 at 7:08am
May 7, 2015 at 8:44am
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/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <algorithm>
#include <string>
#include <map>
#include <functional>

using namespace std;

int main()
{
    map<string, int, std::greater<std::string>> h;

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

    map<string, int>::iterator it;

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

    return 0;
}
May 7, 2015 at 3:33pm
Peter87, can you show me in code this that write.... I'm with difficults!!!
May 7, 2015 at 4:13pm
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.