snippetcppCritical
How can I loop through a C++ map of maps?
Viewed 0 times
mapshowcanloopthroughmap
Problem
How can I loop through a
For example, the above container holds data like this:
How can I loop through this map and access the various values?
std::map in C++? My map is defined as:std::map >For example, the above container holds data like this:
m["name1"]["value1"] = "data1";
m["name1"]["value2"] = "data2";
m["name2"]["value1"] = "data1";
m["name2"]["value2"] = "data2";
m["name3"]["value1"] = "data1";
m["name3"]["value2"] = "data2";How can I loop through this map and access the various values?
Solution
Old question but the remaining answers are outdated as of C++11 - you can use a ranged based for loop and simply do:
this should be much cleaner than the earlier versions, and avoids unnecessary copies.
Some favour replacing the comments with explicit definitions of reference variables (which get optimised away if unused):
Update for C++17: it is now possible to simplify this even further using structured bindings, as follows:
std::map> mymap;
for(auto const &ent1 : mymap) {
// ent1.first is the first key
for(auto const &ent2 : ent1.second) {
// ent2.first is the second key
// ent2.second is the data
}
}this should be much cleaner than the earlier versions, and avoids unnecessary copies.
Some favour replacing the comments with explicit definitions of reference variables (which get optimised away if unused):
for(auto const &ent1 : mymap) {
auto const &outer_key = ent1.first;
auto const &inner_map = ent1.second;
for(auto const &ent2 : inner_map) {
auto const &inner_key = ent2.first;
auto const &inner_value = ent2.second;
}
}Update for C++17: it is now possible to simplify this even further using structured bindings, as follows:
for(auto const &[outer_key, inner_map] : mymap) {
for(auto const &[inner_key, inner_value] : inner_map) {
// access your outer_key, inner_key and inner_value directly
}
}Code Snippets
std::map<std::string, std::map<std::string, std::string>> mymap;
for(auto const &ent1 : mymap) {
// ent1.first is the first key
for(auto const &ent2 : ent1.second) {
// ent2.first is the second key
// ent2.second is the data
}
}for(auto const &ent1 : mymap) {
auto const &outer_key = ent1.first;
auto const &inner_map = ent1.second;
for(auto const &ent2 : inner_map) {
auto const &inner_key = ent2.first;
auto const &inner_value = ent2.second;
}
}for(auto const &[outer_key, inner_map] : mymap) {
for(auto const &[inner_key, inner_value] : inner_map) {
// access your outer_key, inner_key and inner_value directly
}
}Context
Stack Overflow Q#4844886, score: 582
Revisions (0)
No revisions yet.