How can I loop, access and assign through a std::map in C++? My map is defined as:
std::map<std::string, std::map<std::string, int>>
For example, the above container holds data like this:
m["country"]["capital"] = value;
m["country1"]["capital1"] = value;
m["country2"]["capital2"] = value;
based on the country and capital,weather value gets updated
at present if and map is used
map<string,int>mp;
if(Albania)
map[Tirana]= weathervalue;
if("Algeria")
map["Algiers"] = weathervalue;
Any hints,indication and ideas to optimise is always welcome
You can add conditions to this loops but this is the basic way of traversing map inside a map.
Basically map is a structure of key-value pairs so when traversing it you treat it as such. Nested map is the value part of the key-value pair of the original map and as such it is accessed as (name_of_iterator). second.
As m88 suggested: Adds to clarity of the code
Which is the feature of structured bindings added in C++17 standard.
Answer to the additional question.
This is the one way but you can also use first two code snippets (since keyword
auto
detects the type of variable in use).