Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over an STL map inside an STL map?

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.

like image 466
Prasanth Madhavan Avatar asked Dec 23 '10 06:12

Prasanth Madhavan


People also ask

How do I iterate a map in STL?

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.

How do you iterate over a map element?

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.

Can you iterate through a 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.


2 Answers

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)
    {
        /* ... */
    }
}
like image 62
icecrime Avatar answered Sep 28 '22 04:09

icecrime


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 */
    }
}
like image 45
Juraj Blaho Avatar answered Sep 28 '22 04:09

Juraj Blaho