在std :: map中排序,其中key是std :: string [英] sorting in std::map where key is a std::string

查看:141
本文介绍了在std :: map中排序,其中key是std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个std :: map mymap

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";

现在,我想遍历地图并以sorted(键)方式打印值:

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;
}

输出应为:

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?

推荐答案

std :: map 中的元素(默认情况下)由 operator< 应用于键.

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";
}

打印:

hi
hello
how r you

这篇关于在std :: map中排序,其中key是std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆