我如何打印出c++映射值
How can I print out C++ map values?
我有一个这样的map
:
map<string, pair<string, string>> 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->first << " " << it->second.first << " " << it->second.second << "n";
}
在c++ 11中,您不需要拼写map<string, pair<string,string> >::const_iterator
。您可以使用auto
for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "n";
}
注意cbegin()
和cend()
函数的使用。
更简单,您可以使用基于范围的for循环:
for(const auto& elem : myMap)
{
std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "n";
}
从c++ 17开始,你可以使用基于范围的for循环和结构化绑定来迭代你的映射。这提高了可读性,因为您减少了代码中所需的first
和second
成员的数量:
std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };
for (const auto &[k, v] : myMap)
std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;
输出:m[x] = (a, b)
M [y] = (c, d)
Coliru代码
如果你的编译器支持c++ 11,你可以这样做:
for (auto& t : myMap)
std::cout << t.first << " "
<< t.second.first << " "
<< t.second.second << "n";
对于c++ 03,我将使用std::copy
和插入操作符来代替:
typedef std::pair<string, std::pair<string, string> > T;
std::ostream &operator<<(std::ostream &os, T const &t) {
return os << t.first << " " << t.second.first << " " << t.second.second;
}
// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "n"));
您可以尝试基于范围的循环像这样:
for(auto& x:myMap){
cout<<x.first<<" "<<x.second.first<<" "<<x.second.second<<endl;
}
最简单的方法是首先将迭代器声明为map<string ,string> :: iterator it;
,然后使用迭代器从myMap.begin()
遍历映射到myMap.end()
,打印出映射中的键和值对,其中键为it->first
,值为it->second
。
map<string ,string> :: iterator it;
for(it=myMap.begin();it !=myMap.end();++it)
{
std::cout << it->first << ' ' <<it->second;
}
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 如何从多映射中删除特定的重复项
- 在未初始化映射的情况下,将值插入到映射的映射中
- QT通过C++添加映射QML项目
- 在c++中访问int到类对象的映射时出错
- 在C++中搜索嵌套多映射值
- 错误处理.将系统错误代码映射到泛型
- C++匿名结构作为std::映射值
- 如何从存储在std::映射中的std::集中删除元素
- 递归无序映射
- 正在VS调试器中监视映射条目