Jack Jack - 1 year ago 136
C++ Question

How to loop through a C++ map of maps?

How would I loop through a

std::map
in C++?
My map is defined as:

std::map< std::string, std::map<std::string, std::string> >


For example, this 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?

Answer Source

Old question but the remaining answers are outdated as of C++11 - you can use a ranged based for loop and simply do:

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
    }
}

this should be much cleaner than the earlier versions, and avoids unnecessary copies.

Some favor replacing the comments with explicit definitions of reference variables (which get optimized away if unused):

for(auto const& ent1 : mymap) {
    auto& outer_key = ent1.first;
    auto& inner_map = ent1.second;
    for(auto const& ent2 : inner_map) {
        auto& inner_key = ent2.first;
        auto& inner_value = ent2.second;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download