In dealing with a map of maps...
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?
ItecKid
Junior Poster in Training
72 posts since Dec 2008
Reputation Points: 10
Solved Threads: 7
Think of bar->second as a map <string, int> , so simply ...
bar->second["abc"] = 123;
mitrmkar
Posting Virtuoso
1,809 posts since Nov 2007
Reputation Points: 1,105
Solved Threads: 395
If you want to read through all your maps in your map (...), you need two different iterators. One for a map and one for a map >.
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";
}
}
Nick Evan
Not a Llama
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
If you want to read through all your maps in your map (...), you need two different iterators. One for a map and one for a map >.
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?
ItecKid
Junior Poster in Training
72 posts since Dec 2008
Reputation Points: 10
Solved Threads: 7