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
检测正在使用的变量类型)。