C++ 在向量的无序映射上迭代
我知道这是一些基本的东西,但我无法在C++ 在向量的无序映射上迭代,c++,vector,unordered-map,C++,Vector,Unordered Map,我知道这是一些基本的东西,但我无法在std::vectors的无序地图上迭代并打印每个向量的内容。我的无序地图如下所示: std::unordered_map<std::string, std::vector<int> > _dict; 但在尝试打印second属性时,它给了我一个错误。有人知道我怎样才能做到吗?谢谢 可以使用循环的范围打印std::vector的内容: 用于(自动it:\u dict){ std::cout必须为向量使用内部循环 字符串只是一个元素,可
std::vectors
的无序地图
上迭代并打印每个向量的内容。我的无序地图如下所示:
std::unordered_map<std::string, std::vector<int> > _dict;
但在尝试打印second
属性时,它给了我一个错误。有人知道我怎样才能做到吗?谢谢 可以使用循环的范围
打印std::vector的内容
:
用于(自动it:\u dict){
std::cout必须为向量使用内部循环
字符串只是一个元素,可以按原样打印,向量是元素的集合,因此您需要一个循环来打印其内容:
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;
}
}
std::无序映射;
用于(自动和it:_dict)
{
for(auto&i:it.second)//it.second是向量
{
std::cout C++17:基于范围的for循环中的结构化绑定声明
从C++17开始,您可以使用a作为a中的范围声明,并将连续的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;
}
#包括
#包括
#包括
#包括
#包括
#包括
int main(){
常数std::无序映射dict={
{“foo”{1,2,3},
{“bar”{1,2,3}
};
用于(常数自动和[键,v]:dict){
std::难道没有一个标准的方法来流式传输向量,所以你需要写一些具体的东西,这是否回答了你的问题?
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
}
#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;
}