1

如何在 C++ 中通过 std::map 循环、访问和分配?我的地图定义为:

std::map<std::string, std::map<std::string, int>>

例如,上面的容器保存如下数据:

m["country"]["capital"] = value;
m["country1"]["capital1"] = value;
m["country2"]["capital2"] = value;

基于国家和首都,天气值得到更新

目前 if 和 map 被使用

map<string,int>mp;                                                                                              
if(Albania)
map[Tirana]= weathervalue;
if("Algeria")
map["Algiers"] = weathervalue;

任何优化的提示、指示和想法总是受欢迎的

4

2 回答 2

0

你可以像这样遍历

   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
        }
    }
于 2021-05-18T08:39:37.560 回答
0
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检测正在使用的变量类型)。

于 2021-05-18T08:32:58.470 回答