DNamto
DNamto

Reputation: 1362

how to iterate map containing a map in C++

I have a map

map<string, pair<string, string> > MainMap; 
pair<string, string> innerMap;

I would like to iterate the inner map and and outer map to append the html tags to that the captured structure should be in table.

I know that pair doesn't have iterators. Below is the expected algorithm which is not working as pair doesn't support iterators. I would like to what are the possible approaches by which we can get append the values of the map

mainMap m;


void print()
{
    map<string, pair<string, string> >::iterator it;
    pair<string, string>::iterator inner_it;

    char buffer[MAX_PATH];

    GetModuleFileName( NULL, buffer, MAX_PATH );
    string::size_type pos = string( buffer ).find_last_of( "\\/" );
    std::ofstream outputFile(string( buffer ).substr( 0, pos) +"\\test.html"); 


    for ( it=m.begin() ; it != m.end(); it++ ) {
        outputFile << "<tr><td rowspan=3 colspan=1>" <<it->first << "</td>" ;
        for( inner_it=(*it).second.begin(); inner_it != (*it).second.end(); inner_it++)
            outputFile << "<td>" <<(*inner_it).first << "</td><td>" << (*inner_it).second << "</td></tr>";
    }

}

The above algorithm works if we have below map structure which I have tried, but I have to iterate the map discussed above due to design considerations.

map<string, innerMap >::iterator it;
map<string, string>::iterator inner_it;

EDIT :

My structure is like this

enter image description here

Upvotes: 0

Views: 102

Answers (1)

molbdnilo
molbdnilo

Reputation: 66459

Why do you need to iterate a pair? Its length is well known, and its elements are named.

This should do what you want:

for ( it=m.begin() ; it != m.end(); it++ ) {
    outputFile << "<tr><td rowspan=3 colspan=1>" << it->first << "</td>";
    outputFile << "<td>" << it->second.first << "</td><td>" << it->second.second << "</td></tr>";
}

Upvotes: 3

Related Questions