Hello,

If I have code like such:

map <string, map <string, int> > foo;
map <string, map <string, int> >::iterator bar;

How to access the value of the nested map? Normally I access a map's value like such:

bar->second;

To that end, I tried doing this on my nested map:

bar->second->second;

But this gave me complier errors. What is the correct syntax for this?

If you want to read through all your maps in your map (...), you need two different iterators. One for a map <string, int> and one for a map<string, map<string, int> >.
So something like:

map <string, map <string, int> > foo;
// fill map
map <string, map <string, int> >::iterator outerit;
map <string, int>::iterator innerit;
for (outerit = foo.begin(); outerit != foo.end(); ++outerit){
    for (innerit = outerit->second.begin(); innerit != outerit->second.end(); ++innerit){
        cout << outerit->first << " " <<  innerit->first << " " << innerit->second << "\n";
    }
}

If you want to read through all your maps in your map (...), you need two different iterators. One for a map <string, int> and one for a map<string, map<string, int> >.
So something like:

map <string, map <string, int> > foo;
// fill map
map <string, map <string, int> >::iterator outerit;
map <string, int>::iterator innerit;
for (outerit = foo.begin(); outerit != foo.end(); ++outerit){
    for (innerit = outerit->second.begin(); innerit != outerit->second.end(); ++innerit){
        cout << outerit->first << " " <<  innerit->first << " " << innerit->second << "\n";
    }
}

Hello,

Thank you very much for your reply. I have one more question. Due to assignment parameters, the performance of this function must be sub-linear. (i.e, no for loops). So if I have code above, and do this:

outerit = foo.find (some string);

How to move the position of innerit to the value of the key of outerit?

This article has been dead for over six months. Start a new discussion instead.