Jack Jack - 1 month ago 5x
C++ Question

How to loop through a c++ map

How would I loop through a map in c++ i've searched but none seem to work for me.
My map is defined as follows

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

So 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";

So how can I loop through this map and access the various values.


You can use an iterator.

typedef std::map<std::string, std::map<std::string, std::string>>::iterator it_type;
for(it_type iterator = m.begin(); iterator != m.end(); iterator++) {
    // iterator->first = key
    // iterator->second = value
    // Repeat if you also want to iterate through the second map.