简体   繁体   中英

Accessing values of a map that containing a vector pair

I declared a map that contains a vector pair like

typedef vector<pair<string,int>> vectorPair;
map<string,vectorPair> mapName;

I've been trying to iterate through the map with an iterator and I'm confused as to how I access the vector pair from Iterator->first or Iterator->second. Is there a better way to do this?

Here's a neat and tidy way to iterate through the map:

for (auto x : mapName)
{
    vectorPair& vp = x.second;        // or auto&
    ...
}

Live demo at Wandbox

I do not exactly know what you are trying to achieve, but I assume you have a construct that looks something like this:

for(auto i = mapName.begin(); i != mapName.end(); i++)
{

}

and in that loop you simply want to access the vector? That would be done using i->second . If you do not like that syntax you could always use a reference (something like auto &vec = i->second and then only use vec afterwards).

If you want to iterate over the pairs in the vector itself, you would need to use something like this:

for(auto i = mapName.begin(); i != mapName.end(); i++)
{
    for(auto j = i->second.begin(); j != i->second.end(); j++)
    {

    }
}

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