views:

100

answers:

2

Hey guys, I am having trouble trying to get iterators for inner sub-containers.

Basically imagine this simplified code:

typedef map<string, map<string, map> > double_map;

double_map dm;
.. //some code here

for(double_map::iterator it = dm.begin(); it != dm.end(); it++){
    //some code here
    it->first // string
    it->second // <---- this is the 2nd map, how do i get its iterator so I can wrap it 
                       //in a for loop like above?
}

I need to be able to do this without using typedefs for every single inner container, is there a way to get an iterator for the inner container? I have structure that has 4 inner containers and I need to iterate through them all.

Thanks for the help

+3  A: 

(Beware, nothing compiled in the following snippets.)

for(double_map::iterator it = dm.begin(); it != dm.end(); it++){
    //some code here
    it->first; // string
    it->second.begin();
    it->second.end();
}

Edit: I fI understand your comment correctly, you want to get at the type of the iterators of the inner map. If that is so, here's one way:

double_map::mapped_type::iterator inner_iter = it->second.begin();

Off the top of my head, this should work, too:

double_map::value_type::second_type::iterator inner_iter = it->second.begin();
sbi
Sorry that's not what I meant, I mean i need to store those iterators in a inner_type::iterator it2 = it->second.begin()and then loop through using those iterators
iQ
Ahh thats it! Why didn't I think of the mapped_type and value_type, yeah perfect that's what i needed. Thanks!
iQ
But when there are sub-containers 3 or 4 levels deep I guess you have to do double_map::mapped_type::mapped_type::mapped_type hmm, well luckily I have a typedef halfway through
iQ
+1  A: 

Simple:

typedef map<string, map> inner_map; //Typedef for readability
typedef map<string, inner_map > double_map;

double_map dm;
.. //some code here
for(double_map::iterator it = dm.begin(); it != dm.end(); it++){
    //some code here
    it->first // string
    inner_map &innerMap(it->second); //Reference to the inner map for readability
    for(inner_map::iterator it2 = innerMap.begin(); it2 != innerMap.end(); ++it2) {
        //Do whatever you like
    }
}
racha
that was my fallback option but there few levels of sub-containers and I want to keep it a bit generic without using typedefs for each sub-container. Basically i'm trying to do exactly that without the typedef
iQ