gpt4 book ai didi

c++ - 我如何遍历 map vector

转载 作者:太空宇宙 更新时间:2023-11-03 10:22:29 26 4
gpt4 key购买 nike

我编码是为了乐趣。我创建了一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com