我知道这是一些基本的东西,但我无法设法遍历 std::vectors
的 unordered_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::copy
和 std::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/