简体   繁体   English

访问包含向量对的映射的值

[英]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.我一直在尝试使用迭代器遍历地图,但我对如何从 Iterator->first 或 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 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 .这将使用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).如果您不喜欢这种语法,您可以随时使用引用(类似于auto &vec = i->second然后只使用vec之后)。

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++)
    {

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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