简体   繁体   English

将值从Vector插入到Map

[英]Inserting values from Vector to Map

i got some issues trying to put the values of my vector in a new map (maMap) If someone could explain me what contain my ItemIterator or how to do... 我遇到了一些问题,试图将我的向量的值放到新地图(maMap)中,如果有人可以向我解释什么包含我的ItemIterator或如何做...

map<std::string,Employee*> Entreprise::convertiVectorMap() const
{
    map<std::string,Employee*> maMap;
    vector<Employee*>::const_iterator ItemIterator;
    for(ItemIterator = vector_employe.begin(); ItemIterator != vector_employe.end(); ItemIterator++)
    {
        maMap.insert(std::pair<string,Employee*>(ItemIterator->getNom(),ItemIterator));
    }

}

You forgot to derefrence your iterator: 您忘记了取消迭代器的引用:

maMap.insert(std::pair<string,Employee*>((*ItemIterator)->getNom(),*ItemIterator));

And since everyone asks for a revamped version of your code here we go: 由于每个人都要求在这里修改代码,所以我们开始:

map<std::string,Employee*> Entreprise::convertiVectorMap() const
{
    map<std::string,Employee*> maMap;
    for(vector<Employee*>::const_iterator ItemIterator = vector_employe.cbegin(), 
        ItemIteratorEnd = vector_employe.cend(); 
        ItmeIterator != ItemIteratorEnd; ++ItemIterator)
    {
        Employee* ptr = *ItemIterator;
        maMap.insert(std::make_pair(ptr->getNom(),ptr));
    }
}

You can also use ranged based for if you're at least in C++11. 如果您至少在C ++ 11中,也可以使用基于范围的。

Your map is of <std::string, Employee*> , but you are trying to add an iterator as the second element of the pair . 您的映射是<std::string, Employee*> ,但是您试图添加一个迭代器作为pair的第二个元素。 You need to dereference the iterator to get the Employee pointer. 您需要取消引用迭代器以获取Employee指针。

maMap.insert(std::pair<string,Employee*>((*ItemIterator)->getNom(), *ItemIterator));

Or to save from dereferencing the same iterator twice, you could just use a range based for loop. 为了避免两次取消引用同一迭代器,可以只使用基于范围的for循环。 As @CaptainObvlious mentions, you can also use std::make_pair to add to your map . 如@CaptainObvlious所述,您还可以使用std::make_pair添加到map

for(auto const employee: vector_employe)
{
    maMap.insert(std::make_pair(employee->getNom(), employee));
}

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

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