c++ - 我如何遍历 map vector

标签 c++ iterator c++14 stdvector stdmap

我编码是为了乐趣。我创建了一个 map vector ,看看我可以用容器做什么。当我遍历 vector 时,只有 AlfredAngela 出现。如何显示所有 名称?有可能吗?这是我目前所拥有的:

#include <map>
#include <iostream>
#include <conio.h>
#include <vector>
#include <string>

int main()
{
    //create a map
    std::map<std::string, unsigned int> mySuperCoolMap;
    mySuperCoolMap["Edward"] = 39;
    mySuperCoolMap["Daniel"] = 35;
    mySuperCoolMap["Carlos"] = 67;
    mySuperCoolMap["Bobby"]  =  8;
    mySuperCoolMap["Alfred"] = 23;

    std::cout << "\n\n";

    //Ranged based for loop to display the names and age
    for (auto itr : mySuperCoolMap)
    {
        std::cout << itr.first << " is: " << itr.second << " years old.\n";
    }

    //create another map
    std::map<std::string, unsigned int> myOtherSuperCoolMap;
    myOtherSuperCoolMap["Espana"]  =  395;
    myOtherSuperCoolMap["Dominic"] = 1000;
    myOtherSuperCoolMap["Chalas"]  =  167;
    myOtherSuperCoolMap["Brian"]   =  238;
    myOtherSuperCoolMap["Angela"]  = 2300;

    //Display the names and age
    for (auto itr : myOtherSuperCoolMap)
    {
        std::cout << itr.first << " is: " << itr.second << " years old.\n";
    }

    //create a vector of maps
    std::vector<std::map<std::string, unsigned int>> myVectorOfMaps;

    myVectorOfMaps.push_back(mySuperCoolMap);
    myVectorOfMaps.push_back(myOtherSuperCoolMap);

    std::cout << "\n\n";

    //Display the values in the vector
    for (auto itr : myVectorOfMaps)
    {
        std::cout << itr.begin()->first << " is: " << itr.begin()->second << " years old.\n";
    }

    _getch();
    return 0;
}

最佳答案

您需要使用嵌套循环。使用调试器并打印 itr如果您正在学习新概念,可能会给您这种直觉。

//Display the values in the vector
for (const auto &vec : myVectorOfMaps)
{
    for (const auto &p : vec)
    {
        std::cout << p.first << " is: " << p.second << " years old.\n";
    }
}

Demo

你要求只打印第一个元素,这就是为什么你只得到第一个元素。请注意,这是一个错误,因为您在访问 map 的第一个元素时未确保 map 是否为非空。


注意 <conio.h>不是标准 header ,可能不适用于标准平台

关于c++ - 我如何遍历 map vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424870/

相关文章:

c++ - 如何在redhawk上添加一个关于idl的项目

c++ - STL 中 next_permutation 的 Python 实现

c++ - 将 shared_ptr<StructA> 移动到 shared_ptr<variant<StructA, StructB>>

c++ - 写入系统调用 unix 不会写入来自 argv 的所有文本

c++ - 禁止复制操作是否自动禁止 move 操作?

c++ - 如何从 STL 数据结构中删除 reverse_iterator?

ruby - 迭代 Excel 工作簿并对所有内容建立索引?

c++ - 如何正确实现 C++ 类析构函数

c++ - 从 lambda 获取捕获的变量?

c++ - 迭代器默认构造函数和 POD 成员初始化