【问题标题】:Iterating over unordered_map of vectors遍历向量的 unordered_map
【发布时间】:2020-06-27 19:05:47
【问题描述】:

我知道这是一些基本的东西,但我无法遍历 unordered_mapstd::vectors 并打印每个向量的内容。我的unordered_map 看起来像这样:

std::unordered_map<std::string, std::vector<int> > _dict;

现在我可以打印地图的first 属性:

for (auto &it : _dict)
{
    std::cout << it.first <<std::endl;
}

但在尝试打印 second 属性时出现错误。有谁知道我怎么能做到这一点?谢谢!

【问题讨论】:

标签: c++ vector unordered-map


【解决方案1】:

C++17:基于范围的 for 循环中的结构化绑定声明

从 C++17 开始,您可以使用structured binding declaration 作为range-based for loop 中的范围声明,同时使用std::copystd::ostream_iterator 来编写连续的std::vector元素到std::cout:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <unordered_map>
#include <vector>

int main() {
    const std::unordered_map<std::string, std::vector<int> > dict =  {
        {"foo", {1, 2, 3}},
        {"bar", {1, 2, 3}}
    };
    
    for (const auto& [key, v] : dict) {
        std::cout << key << ": ";
        std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
        std::cout << "\n";
    } 
    // bar: 1 2 3 
    // foo: 1 2 3 
    
    return 0;
}

【讨论】:

    【解决方案2】:

    您必须对向量使用内部循环。

    字符串只是一个元素,可以按原样打印,向量是元素的集合,所以你需要一个循环来打印它的内容:

    std::unordered_map<std::string, std::vector<int>> _dict;
    
    for (auto &it : _dict)
    {
        for (auto &i : it.second) // it.second is the vector
        {
            std::cout << i;
        }
    }
    

    如果您想打印向量中的特定项目,您需要访问要打印的项目的位置:

    for (auto &it : _dict)
    {
        std::cout << it.second.at(0) << std::endl; //print the first element of the vector
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用range-for loop 打印std::vector &lt;int&gt; 的内容:

      for(auto it : _dict){
          std::cout << it.first << ": ";
      
          for(int item : it.second){
              std::cout << item << " ";
          }
          std::cout << std::endl;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-12
        • 1970-01-01
        相关资源
        最近更新 更多