【问题标题】:How do I iterate through a vector of maps如何遍历地图向量
【发布时间】:2019-10-17 04:21:08
【问题描述】:

我编码是为了好玩。我创建了一个地图矢量,看看我可以用容器做什么。当我遍历向量时,只有 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;
}

【问题讨论】:

  • 可能是嵌套循环?因此,首先循环遍历向量,然后在该循​​环内遍历地图。
  • (旁注:)最好完全避免使用conio.h,如果您需要在Windows 下保持终端打开,只需使用标准C 库中的getchar()
  • 命名:for (auto itr : mySuperCoolMap):itr 不是迭代器,而是一个值(在您的情况下是一对),pitr 更好。 (在 C++17 中,您甚至可以使用 for (const auto&amp; [name, age] : mySuperCoolMap))。

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


【解决方案1】:

您需要使用嵌套循环。如果您正在学习新概念,使用调试器并打印 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 是否为非空。


请注意,&lt;conio.h&gt; 不是标准标头,可能不适用于标准平台

【讨论】:

  • 您的循环应该使用引用进行迭代以避免复制所有涉及的对象:for (auto &amp;vecitr : myVectorOfMaps) { for (auto &amp;mapitr : vecitr) { ... }
  • 非常感谢。我得到了你的建议@GyaptiJain。
  • 谢谢@RemyLebeau。我总是忘记那些参考资料。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 2014-06-11
    • 2021-02-27
    • 1970-01-01
    相关资源
    最近更新 更多