简体   繁体   中英

Get the key and values of map elements in a vector of maps from a constant iterator to the vector of maps

I have a vector of maps containing strings .,ie,

vector< map <string,string> > vectorOfMaps;

vector< map <string,string> >::const_iterator itr =vectorOfMaps.begin();

vectorOfMaps is filled in another function and the caller function can access only the const_iterator itr.

How do i access the key and its respective value of each map element in the vectorOfMaps?

Any help appreciated:)

EDIT: Got my solution.

map<string,string> myMap = (*itrVectorOfMaps);

while(loop till the end element)
{
    for(map<string,string>::iterator itM = myMap.begin();   
                                    itM != myMap.end(); itM++)

    {
        cout<<"Key="<<itM->first<<" => Value="<<itM->second<<endl;
    }
    itrVectorOfMaps++;
    myMap=(*itrVectorOfMaps);
}

You can use the first and second keywords to access the map elements as you're iterating over the vector of map s.

for(auto const& currentMap : vectorOfMaps)  // Loop over all the maps
{
    for(auto const& element : currentMap)   // Loop over elements of current map
    {
        std::string const& key = element.first;
        std::string const& value = element.second;
    }
}

Your solution is bad because you make multiple copies of maps, first one just before the loop and then inside the loop. Consider this shorter and faster version:

for (auto const& el: *itrVectorOfMaps)
    cout << "Key=" << el.first << " => Value=" << el.second << endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM