如何打印C ++映射值? [英] How can I print out C++ map values?
本文介绍了如何打印C ++映射值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的map
:
map<string, pair<string,string> > myMap;
然后我使用以下命令将一些数据插入了地图:
And I've inserted some data into my map using:
myMap.insert(make_pair(first_name, make_pair(middle_name, last_name)));
我现在如何打印出地图中的所有数据?
How can I now print out all the data in my map?
推荐答案
for(map<string, pair<string,string> >::const_iterator it = myMap.begin();
it != myMap.end(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}
在C ++ 11中,您不需要拼写map<string, pair<string,string> >::const_iterator
.您可以使用auto
In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator
. You can use auto
for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}
请注意cbegin()
和cend()
函数的使用.
更容易的是,您可以使用基于范围的for循环:
Easier still, you can use the range-based for loop:
for(auto elem : myMap)
{
std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}
这篇关于如何打印C ++映射值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文