【问题标题】:Iterating through a vector of maps遍历地图向量
【发布时间】:2018-05-08 06:56:14
【问题描述】:

我是学习 c++ 的新手,我在尝试迭代我的代码时遇到了麻烦。

vector<map<string, char>> skills;
map<string, char> frontFloat;
map<string, char> frontGlide;

skills.push_back(frontFloat);
skills.push_back(frontGlide);

frontFloat["Wetface"]='C';
frontFloat["relaxed"]='C';
frontFloat["comfortable"]='I';

// ...

for (auto x : skills) {
   for (auto it=x.begin(); it!=x.end(); ++it){
      cout<< it->first << " => " << it->second << '\n';
   }
}

我正在尝试遍历 vector 并进一步遍历向量中的每个 map

我的for 循环似乎没有打印任何内容,我已将值推送到地图中。请指教。

【问题讨论】:

  • 你能展示一下你是如何插入这些值的吗?
  • 您的示例不会将任何内容推送到地图中。这很可能就是问题所在,这就是您应该展示的内容。顺便说一句,auto x : skills 复制每张地图,当有大量数据要复制时,你不想这样做。
  • 由于您使用了hashmap 标签,我想指出std::map 不是 哈希图!它是一个自平衡二叉搜索树(即红黑树)。对于哈希图,请使用 std::unordered_map
  • “并且我已将值推送到地图中” - 不是在您发布的代码中您没有。请尽可能将示例代码发布为minimal reproducible example
  • 与您的问题无关,但您很可能想要auto&amp; xconst auto&amp; x

标签: c++ vector hashmap iteration


【解决方案1】:
skills.push_back(frontFloat);
// ...
frontFloat["Wetface"]='C';

您设置WetFacemapvector 中的不同。您在vector 中制作frontFloat副本

因此,当您对map 内部 vector 进行交互时,您在其中设置元素的map 是不一样的。

要添加到 vector 内的地图,请执行以下操作

skills.back()["WetFace"] = 'C';

【讨论】:

    【解决方案2】:

    除了 BoBTFish 的答案,使用向量元素的索引来操作它们。

    vector<map<string, char>> skills;
    map<string, char> frontFloat;
    map<string, char> frontGlide;
    
    skills.push_back(frontFloat);
    skills.push_back(frontGlide);
    
    skills[0]["Wetface"]='C';
    skills[0]["relaxed"]='C';
    skills[0]["comfortable"]='I';
    
    for (auto& x : skills) {
       for (auto& skillPair : x){
          cout<< skillPair.first << " => " << skillPair.second << '\n';
       }
    }
    

    【讨论】:

      【解决方案3】:
      skills.push_back(frontFloat);
      skills.push_back(frontGlide); //this will actually be stored as value not as reference. so the vector will contain only values from map at the pushing into the vector. But in your case you can push that as reference.
      

      下面的代码使用指针引用对您的代码稍作修改。

      vector<map<string, char>*> skills; //here I'm storing the address of the map not the value.
      map<string, char> frontFloat;
      map<string, char> frontGlide;
      
      skills.push_back(&frontFloat); //here i'm pushing the address to the vector.
      skills.push_back(&frontGlide);
      
      frontFloat["Wetface"]='C';
      frontFloat["relaxed"]='C';
      frontFloat["comfortable"]='I';
      
      // ...
      
      for (auto x : skills) {
         for (auto it=(*x).begin(); it!=(*x).end(); ++it){ //(*x) dereferencing the map address to the value.
            cout<< it->first << " => " << it->second << '\n';
         }
      }
      return 0;
      }
      

      这将根据您的需要工作。并且每当您遍历向量时,您只会获得地图的当前值。我希望这会对你有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多