c++ - 如何打印出 C++ 映射值?

标签 c++ dictionary for-loop printing std-pair

我有一个像这样的 map:

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

我已经在我的 map 中插入了一些数据:

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

我现在如何打印 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

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++ - 如何打印出 C++ 映射值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14070940/

相关文章:

c++ - 错误 : expected unqualified-id before & token

c++ - 为什么 std::ostreambuf_iterator 截断整数?

c# - C# 字典的原子 AddOrUpdate

JavaScript 函数不检索数组元素

python - 将具有一个共同元素的列表列表组合在一起并保存到单独的文本文件中(python)

java - 使用 for 循环而不是应用 Math.pow 方法计算功率

C++ Builder 字符数组寻址

c++ - 我可以在没有鼠标事件的情况下获取 OpenCV 中的鼠标位置吗?

Python:如何从键值字典列表构造元组值字典?

java - 以对象值作为键的 HashMap