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 << "
";
}
在C++11中,你不需要拼出map.您可以使用 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 << "
";
}
注意 cbegin() 和 cend() 函数的使用.
Note the use of cbegin() and cend() functions.
更简单的是,您可以使用基于范围的 for 循环:
Easier still, you can use the range-based for loop:
for(const auto& elem : myMap)
{
std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "
";
}
这篇关于如何打印出 C++ 地图值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何打印出 C++ 地图值?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
