【问题标题】:Accessing values of a map that containing a vector pair访问包含向量对的地图的值
【发布时间】:2018-09-26 22:07:32
【问题描述】:

我声明了一个包含向量对的地图

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

我一直在尝试使用迭代器遍历地图,但我对如何从 Iterator->first 或 Iterator->second 访问向量对感到困惑。有没有更好的方法来做到这一点?

【问题讨论】:

  • 显示试图遍历地图的代码

标签: c++ dictionary vector std-pair


【解决方案1】:

这是一种简洁的方式来遍历地图:

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

Wandbox现场演示

【讨论】:

    【解决方案2】:

    我不完全知道您想要实现什么,但我假设您有一个看起来像这样的构造:

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

    在那个循环中你只是想访问向量?这将使用i-&gt;second 完成。如果您不喜欢这种语法,您可以随时使用引用(例如 auto &amp;vec = i-&gt;second,然后只使用 vec)。

    如果你想遍历向量本身中的对,你需要使用这样的东西:

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

    【讨论】:

    • 如果你的编译器有auto 可用,那么它也有ranged-based for loops 可用,所以你应该使用它而不是直接使用迭代器:for(auto &amp;v : mapName) { for(auto &amp;p : v.second) { /* use p as needed ...*/ } }
    猜你喜欢
    • 2018-01-08
    • 1970-01-01
    • 2011-08-09
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多