c++ - 迭代 vector 的 unordered_map

标签 c++ vector unordered-map

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

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

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

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

但是当我尝试打印 second 属性时它给了我一个错误。有谁知道我怎么能做到这一点?谢谢!

最佳答案

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

从 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;
}

关于c++ - 迭代 vector 的 unordered_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62614386/

相关文章:

c++ - 如何用固定元素直接初始化unordered_map?

python - 指向外部托管的 C++ 智能指针(例如 : Python) resources?

R:如何通过仅比较每个字符串中的前 3 个制表符分隔项来对两个字符串向量使用 setdiff?

c++ - 在控制台上打印 vector

c++ - std::move(key) 在迭代 unordered_map<string, string> 时?

c++ - 构造一个 unordered_map,值为一对字符串和对象类型

c++ - NEON 向量化无符号字节乘积和 : (a[i]-int1) * (b[i]-int2)

c++ - C++中纯虚函数的用途是什么?

c++ - vector.erase() 和 remove_if() 有问题

c++ - move unique_ptr<T> 的 vector