How can I iterate over an STL map inside an STL map?
If c++11 is available, we could use stl algorithm for_each and lambda functions to get a elegant solution
typedef map<int, string> INNERMAP;
typedef map<string, INNERMAP> OUTERMAP;
OUTERMAP theMapObject;
// populate the map object
// iterate the map object now
std::for_each(theMapObject.cbegin(), theMapObject.cend(),
[](const OUTERMAP::value_type& outerMapElement)
{
// process the outer map object
const INNERMAP& innerMapObject = outerMapElement.second;
std::for_each(innerMapObject.cbegin(), innerMapObject.cend(),
[](const INNERMAP::value_type& innermapElemen)
{
//process the inner map element
});
});
While it's not clear what problem you are solving by having a map inside a map, I don't think there is a better way of iterating on all the items without using these iterators. The only thing you can do to improve code readability is to use typedefs on the template types.
However, won't it be a better idea to define your map
as
multimap <string, MyClass>
where MyClass
is defined as a pair of integer and a string, as well as a toString() method to dump the contents, etc?
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 */
}
}
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)
{
/* ... */
}
}