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

The elements in std::map are ordered (by default) by operator< applied to the key.

The code you posted, with minor edits, worked for me as you expected:

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

for (std::map<string, string>::iterator i = mymap.begin(); i != mymap.end(); i++)
{
    cout << i->second << "\n";
}

Prints:

hi
hello
how r you

Leave a Comment