将多个地图与矢量组合成一个地图

时间:2015-01-23 19:17:41

标签: c++ dictionary vector stdmap

我有一个关于组合将矢量作为值部分的地图的问题。例如,我可能会有以下内容:

std::map<int, std::vector<Affector*> > affectors;

我想通过组合多个较小的地图来构建此地图。例如:

for (auto ch = chList.begin(); ch != chList.end(); ++ch)
{
    std::map<int, std::vector<Affector*> > tempAff = ch->getemng()->getAffectorsInOrder();
    std::map<int, std::vector<Affector*> > tempAff2 = ch->getpmng()->getAffectorsInOrder()
    //I want to append both of these maps to the top level affectors map
}

我能想到明显的解决方案

for (auto ch = chList.begin(); ch != chList.end(); ++ch)
{
    std::map<int, std::vector<Affector*> > tempAff = ch->getemng()->getAffectorsInOrder();
    for (auto aff = tempAff.begin(); aff != tempAff.end(); ++aff)
    {
        affectors[aff->first].push_back(aff->second);
    }
    tempAff.clear();
    tempAff = ch->getpmng()->getAffectorsInOrder();
    for (auto aff = tempAff.begin(); aff != tempAff.end(); ++aff)
    {
        affectors[aff->first].push_back(aff->second);
    }
    ...
}

这会起作用,但感觉效率低下。我不能使用地图的插入操作,因为我需要保留向量中的现有值。有没有更好的方法来组合我没想到的地图?

由于

1 个答案:

答案 0 :(得分:3)

Richard Corden所述,我认为你真的想要使用std::multimap

std::multimap<int, Affector*> affectors;

如果您还可以执行tempAfftempAff2 std::multimap

affectors.insert(tempAff.begin(), tempAff.end());
affectors.insert(tempAff2.begin(), tempAff2.end());
相关问题