我有一个C++程序,它有一个unordered_map (unmap_graph),它的值为vector (vector_id_as2),而vector是另一个unordered_map (unmap_id_as2),其值为int。查看下面的C++代码:
typedef unordered_map<int, std::vector<int>> unmap_id_as2;
typedef vector<unmap_id_as2> vector_id_as2;
typedef unordered_map<int, vector_id_as2> unmap_graph;
unmap_id_as2 map2_1;
map2_1[67031]={1,432414};
unmap_id_as2 map2_2;
map2_2[67030]={2,432413};
unmap_id_as2 map2_3;
map2_3[67053]={2,432444};
unmap_id_as2 map2_4;
map2_4[67053]={3,432445};
vector_id_as2 vetor_id_as2 = {map2_1, map2_2, map2_3, map2_4};
unmap_graph map1;
map1[67029] = vetor_id_as2;
cout << "***********: 432414 - " << map1[67029][0][67031][1] << endl;
cout << "***********: 2 - " << map1[67029][1][67030][0] << endl;
cout << "***********: 432413 - " << map1[67029][1][67030][1] << endl;
cout << "***********: 3 - " << map1[67029][3][67053][0] << endl;我的问题是:如何在map1中循环获取内部映射(unmap_id_as2)键和值?例如,在cout << "***********: 432414 - " << map1[67029][0][67031][1] << endl;命令中,一个得到的结果是432414。但我通知了所有的map1护理人员(6702967031)去做。因此,我想知道如何在map1中循环得到它的所有值(这是另一个unordered_map的向量)?
爱默生
发布于 2020-10-07 18:46:55
你有
typedef unordered_map<int, std::vector<int>> unmap_id_as2;
typedef vector<unmap_id_as2> vector_id_as2;
typedef unordered_map<int, vector_id_as2> unmap_graph;因此,在unmap_graph上循环按相反顺序进行:
for (auto& [my_int, my_vector_id_as2] : map1)
for (auto& my_unmap_id_as2 : my_vector_id_as2)
for (auto& [my_inner_int, my_vector_ints] : my_unmap_id_as2)
{
std::cout << my_inner_int << ":";
for (int my_innermost_int : my_vector_ints)
std::cout << " " << my_innermost_int;
std::cout << '\n';
}(如果不需要修改/更改数据,可以考虑使用const auto&)。
发布于 2020-10-07 17:22:01
您可以在远程环路中使用C++迭代映射。
std::unordered_map<int,std::string> names{
{1,"John"},
{3,"Geoff"},
{2,"Parekh"},
};
//Iterating through the map
for (auto [key,value] : names)
{
std::cout << key << " : " << value << '\n';
}输出:
2 : Parekh
3 : Geoff
1 : John如果要循环嵌套映射(其中一个值是另一个映射),则还需要嵌套这些循环。
for (auto [key,value] : names)
{
//value is now the vector of un_ordered map
for( auto map : value){
for (auto [key2,value2] : map)
{
/// .....
}
}
}这是查看容器中每个映射的唯一方法,我建议您重新考虑容器的选择,因为这将是高效的。
https://stackoverflow.com/questions/64248957
复制相似问题