gpt4 book ai didi

c++ - 在迭代 map 时向/从 map 添加/删除元素是否安全

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:55:05 26 4
gpt4 key购买 nike

在迭代 map 时,向 map 添加/删除元素是否安全?请看下面的伪代码:

       //Pseudo Code
//test is a global variable
map<int, CustomClass*> test;
test[Index1] = new CustomClass;
test[Index2] = new CustomClass;
test[Index3] = new CustomClass;

...
//Iterating the map
map<int, CustomClass*>::iterator itor;
itor = test.begin();
while(itor != test.end())
{
if (itor->first == IndexToRemove)
{
//below function will remove
//element from the map
RemoveFromMap(IndexToRemove);
}

if (NeedAddNewElement())
{
//below function will add
// an element to the map
AddNewElement(IndexToAdd);
}

itor++;
}

//Remove a mapping from map
void RemoveFromMap(int index)
{
map<int, CustomClass*>::iterator itor;
itor = test.begin();
while(itor != test.end())
{
if (itor->first == index)
{
test.erase(itor);
break;
}

itor++;
}
}

//add new mapping to map
void AddNewElement(int index)
{
//chech if index exists
if (test.find(index) == test.end())
{
test[index] = new CustomClass;
}
}

最佳答案

在遍历容器并删除元素时,迭代器指向的迭代器本身变得无效!

因此:

iterator = container.erase(iterator)

获取下一个有效的迭代器。

关于c++ - 在迭代 map 时向/从 map 添加/删除元素是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20996963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com