我知道这是一些基本的东西,但我无法在unordered_map of std::vectors上迭代并打印每个向量的内容。我的unordered_map看起来是这样的:
std::unordered_map<std::string, std::vector<int> > _dict;现在,我只需打印地图的first属性:
for (auto &it : _dict)
{
std::cout << it.first <<std::endl;
}但是,当试图打印second属性时,它会给我一个错误。有人知道我是怎么做到的吗?谢谢!
发布于 2020-06-27 19:30:05
C++17:基于范围的for循环中的结构化绑定声明
从C++17开始,您可以使用作为中的范围声明,以及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;
}发布于 2020-06-27 19:10:35
必须对向量使用内循环。
字符串只是一个元素,可以按原样打印,向量是元素的集合,因此您需要一个循环来打印其内容:
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
}发布于 2020-06-27 19:08:57
您可以使用range-for loop打印std::vector <int>的内容。
for(auto it : _dict){
std::cout << it.first << ": ";
for(int item : it.second){
std::cout << item << " ";
}
std::cout << std::endl;
}https://stackoverflow.com/questions/62614386
复制相似问题