Alex Rivera | Logout

sorting in std::map where key is a std::string

Asked 2011-12-13T13:54:39.110
28

I have a std::map mymap

Now, if I insert values in the map like:

std::map <string, string> mymap;
mymap["first"] = "hi";
mymap["third"] = "how r you";
mymap["second"] = "hello";

Now I want to iterate over the map and print the value in sorted(keys) manner:

map<string, string>::iterator itr;
for(itr = mymap.begin(); itr != mymap.end(); itr++)
{
   string newline = itr->second;
   cout << newline << endl;
}

Output should be:

hi 
hello 
how r you 

I thought that by default map stores in sorted keys manner but I'm getting the same order in output as I'm giving in input. Do I need to provide my sort function for this or need to do something extra before iterating over the map?

Edit
Report

1 Answer

9

The map is actually a tree, and is sorted by KEY order. You are printing itr->second which is the VALUE not the KEY. If you want your key/value pairs sorted by VALUE, use the VALUE as key instead, or store everything in another container (say an array), then sort them.

answered 2011-12-13T14:12:04.043

Your Answer