0

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?

3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by ItecKid
0

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";
    }
}
0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.