【发布时间】:2019-10-17 04:21:08
【问题描述】:
我编码是为了好玩。我创建了一个地图矢量,看看我可以用容器做什么。当我遍历向量时,只有 Alfred 和 Angela 出现。如何显示所有名称?甚至可能吗?这是我目前所拥有的:
#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不是迭代器,而是一个值(在您的情况下是一对),p比itr更好。 (在 C++17 中,您甚至可以使用for (const auto& [name, age] : mySuperCoolMap))。
标签: c++ iterator c++14 stdvector stdmap