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

2019-03-11 06:59发布

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?

标签: c++ stl
4条回答
冷血范
2楼-- · 2019-03-11 07:06

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.

查看更多
Animai°情兽
3楼-- · 2019-03-11 07:11

The standard defines:

The fundamental property of iterators of associative containers is that they iterate through the containers in the non-descending order of keys where non-descending is defined by the comparison that was used to construct them.

查看更多
\"骚年 ilove
4楼-- · 2019-03-11 07:15

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
查看更多
Summer. ? 凉城
5楼-- · 2019-03-11 07:24

std::map is already ordered. If you were using unordered_map, now you'd have a problem!

Entries in std::map are ordered by the key, or itr->first. itr->second as you have it, refers to the value associated with the key.

Further more, you're not iterating over the map, you're iterating over file_line (I don't know what that is, but I'm going to assume it's different from mymap. That is what you should be iterating over).

查看更多
登录 后发表回答