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?
use
std::map< std::string, std::map<std::string, std::string> >::const_iterator
when map is const.or nicer in C++0x:
Do something like this:
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):
C++11:
output:
In C++17, you will be able to use the "structured bindings" feature, which lets you define multiple variables, with different names, using a single tuple/pair. Example:
The original proposal (by luminaries Bjarne Stroustrup, Herb Sutter and Gabriel Dos Reis) is fun to read (and the suggested syntax is more intuitive IMHO); there's also the proposed wording for the standard which is boring to read but is closer to what will actually go in.