Reputation: 13
I have a C++ program that has one unordered_map
(unmap_graph) with a vector
in its value (vector_id_as2), and this vector
is another unordered_map
(unmap_id_as2) with a vector
of int in its value. Look at C++ code below:
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;
My question is: How can I loop in map1 to get inside map (unmap_id_as2
) keys and values? For example, at cout << "***********: 432414 - " << map1[67029][0][67031][1] << endl;
command, a got the result 432414. But I informed all map1 parametes ([67029][0][67031][1]) to do it. So I want to know how can I loop in map1 to get all its values (that is a vector of another unordered_map)?
Emerson
Upvotes: 1
Views: 1307
Reputation: 106244
You have
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;
So looping over an unmap_graph
happens in the reverse order:
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';
}
(Consider using const auto&
s if you don't need to mutate/change data).
Upvotes: 2
Reputation:
you can use Ranged-based-loops in C++ to iterate through the map
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';
}
Output:
2 : Parekh
3 : Geoff
1 : John
If you want to loop through nested maps, where the value of one is another map, you need to nest the loops too.
for (auto [key,value] : names)
{
//value is now the vector of un_ordered map
for( auto map : value){
for (auto [key2,value2] : map)
{
/// .....
}
}
}
This is the only way you can go through every map in the container, I do suggest that you rethink your container choice as this will be highly in-efficient.
Upvotes: 0