问题描述
如何在 C++ 中通过 std::map 循环、访问和分配?我的地图定义为:
std::map<std::string,std::map<std::string,int>>
例如上面的容器保存的数据是这样的:
m["country"]["capital"] = value;
m["country1"]["capital1"] = value;
m["country2"]["capital2"] = value;
根据国家和首都,更新天气值
目前如果使用和地图
map<string,int>mp;
if(Albania)
map[Tirana]= weathervalue;
if("Algeria")
map["Algiers"] = weathervalue;
任何优化的提示、指示和想法总是受欢迎的
解决方法
for(auto& it:mp){
for(auto& it1: it.second){
it1.second=weathervalue;
}
您可以向此循环添加条件,但这是在地图内遍历地图的基本方式。
基本上 map 是一个键值对的结构,所以当你遍历它时,你就这样对待它。嵌套映射是原始映射的键值对的值部分,因此它被访问为 (name_of_iterator)。 第二个。
正如 m88 建议的那样: 增加代码的清晰度
for(auto& [country,submap]:mp){
for(auto& [capital,wetherValue]: submap){
wetherValue=New_Weather_Value;
}
这是 C++17 标准中添加的结构化绑定的特性。
回答附加问题。
typedef map<string,int> mp;
//note that you gave the alias mp to the map so you can not use it as as variable name
void function(){
int new_value=50; // some value
mp::iterator inner; // iterator of inner map
map<int,mp> mymap; // main map
map<int,mp>::iterator outer; // iterator of the main map
for (outer=mymap.begin();outer!=mymap.end();outer++){
for(inner=outer->second.begin();inner!=outer->second.end();inner++)
inner->second= new_value;
//do some other stuff
}
}
//Additionally note that you must use the smart pointer in the case of nested maps
这是一种方法,但您也可以使用前两个代码片段(因为关键字 auto
检测正在使用的变量类型)。
你可以这样穿越
std::map< std::string,std::map<std::string,int> > myMap;
for(auto& iter : myMap)
{
for(auto& childIter : iter.second)
{
// do here what you want i.e
if(childIter.first == "xyz")
childIter.second = 20;
}
}
// OR
for(auto& [country,map] : myMap)
{
for(auto& [capital,weather] : map)
{
if(capital == "xyz")
weather = 20;
}
}
另一种方式
typedef map<string,int> innermap;
std::map< std::string,innermap > myMap;
for(auto iterOuter = myMap.begin(); iterOuter != myMap.end(); iterOuter++)
{
for(map<string,int>::iterator iterInner = iterOuter->second.begin(); iterInner != iterOuter->second.end(); iterInner++)
{
// do here what you want
}
}