iQ.
iQ.

Reputation: 3953

Getting the Iterator for an inner STL Container?

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.

Upvotes: 0

Views: 185

Answers (2)

sbi
sbi

Reputation: 224059

(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();

Upvotes: 3

rluba
rluba

Reputation: 2044

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
    }
}

Upvotes: 1

Related Questions