C ++打印出地图值 [英] C++ printing out map values

查看:170
本文介绍了C ++打印出地图值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个这样的地图:

  map< string,pair& > myMap; 

我在地图中插入了一些数据:

  myMap.insert(make_pair(first_name,make_pair(middle_name,last_name))); 

我的问题是,如何打印我的地图中的所有数据?
请提供一个例子供我参考。

解决方案

  for(map< string,pair&string; string> const_iterator it = myMap.begin(); 
it!= myMap.end(); ++ it)
{
std :: cout<第一<< < it-> second.first<< <第二 - 第二 - \\\
;
}

在C ++ 11中,您不需要拼写 map< string,pair< string,string> > :: const_iterator 。您可以使用 auto

  for(auto it = myMap.cbegin ); it!= myMap.cend(); ++ it)
{
std :: cout<第一<< < it-> second.first<< <第二 - 第二 - \\\
;
}

注意使用 cbegin更简单的是,你可以使用基于范围的for循环()函数。code>和 cend()

  for(auto elem:myMap)
{
std :: cout< elem.first<< < elem.second.first<< < elem.second.second<< \\\
;
}


So I have a map like this:

map<string, pair<string,string> > myMap;

And I've inserted some data in my map using:

myMap.insert(make_pair(first_name, make_pair(middle_name, last_name)));

My question is, how do I print out all the data in my map? Please provide an example for my reference.

解决方案

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

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

Note the use of cbegin() and cend() functions.

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屋!

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