I have an STL map definition as follows:
map<string, map<int, string> > info;
I iterate that map using the following code:
for( map<string, map<int, string> >::iterator ii=info.begin(); ii!=info.end(); ++ii){
for(map<int, string>::iterator j=ii->second.begin(); j!=ii->second.end();++j){
cout << (*ii).first << " : " << (*j).first << " : "<< (*j).second << endl;
}
}
Is this the correct way to iterate or is there a better way to do so? The above code works for me, but I'm looking for a more elegant solution.
Iterating over a map by using STL Iterator:By creating an iterator of std::map and initializing it to the starting of map and visiting upto the end of map we can successfully iterate over all the elements of map.
Iterating over Map. entrySet() method returns a collection-view(Set<Map. Entry<K, V>>) of the mappings contained in this map. So we can iterate over key-value pair using getKey() and getValue() methods of Map.
To iterate over a Map, we can use for..of and forEach() loop constructs. Map provides three methods that return iterable: map. keys(), map. values() and map.
This is correct, it just lacks a few typedef
and readability improvements :
typedef std::map<int, std::string> inner_map;
typedef std::map<std::string, inner_map> outer_map;
for (outer_map::iterator i = outerMap.begin(), iend = outerMap.end(); i != iend; ++i)
{
inner_map &innerMap = i->second;
for (inner_map::iterator j = innerMap.begin(), jend = innerMap.end(); j != jend; ++j)
{
/* ... */
}
}
If C++11 is available you may use range for
loop:
for(auto &i: info) {
for(auto &j: i.second) {
/* */
}
}
If only C++11 auto
is available:
for( auto i=info.begin(); i!=info.end(); ++i) {
for( auto j=i->second.begin(); j!=i->second.end(); ++j) {
/* */
}
}
If you may use BOOST there is BOOST_FOREACH:
typedef std::map<int, std::string> inner_map;
typedef std::map<std::string, inner_map> outer_map;
outer_map outer;
BOOST_FOREACH(outer_map::value_type &outer_value, outer){
BOOST_FOREACH(inner_map::value_type &inner_value, outer_value->second){
/* use outer_value and inner_value as std::pair */
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With