我如何遍历地图矢量

问题描述 投票:0回答:2

我编码很有趣。我创建了一个地图矢量来查看我可以使用容器做什么。当我遍历向量时,仅显示AlfredAngela。如何显示all名称?可能吗这是我到目前为止的内容:

#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;
}
c++ iterator c++14 stdvector stdmap
2个回答
2
投票

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

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

Demo

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


请注意,conio不是标准头,并且可能不适用于标准平台


0
投票

您在for循环中获得的对象是std::map。因此,您需要使用另一个for循环来遍历每个映射中的所有条目。

© www.soinside.com 2019 - 2024. All rights reserved.