简体   繁体   English

在迭代时插入std :: map?

[英]Inserting into std::map while iterating over it?

I have a Map over which I iterate like this: 我有一个地图,我迭代这样:

std::map<unsigned int, GameObject *>::iterator itr = _gameObjects.begin();
    while (itr != _gameObjects.end())
    {
        itr->second->Update();
        itr++;
    }

Update() might insert an element into the map or even remove one from it, but it doesn't necessarily do any of the two. Update()可能会将一个元素插入到地图中,甚至可以从中删除一个元素,但它不一定会执行这两个元素中的任何一个。 It obviously doesn't work like that. 它显然不会那样工作。 Is there a way it can be done? 有没有办法可以做到?

From std::map::erase() : std::map::erase()

References and iterators to the erased elements are invalidated. 擦除元素的引用和迭代器无效。 Other references and iterators are not affected. 其他引用和迭代器不受影响。

From std::map::insert() : std::map::insert()

No iterators or references are invalidated. 没有迭代器或引用无效。

From std::map::operator[] : 来自std::map::operator[]

No iterators or references are invalidated. 没有迭代器或引用无效。

If Update() does not remove itself, then the code is legal. 如果Update()没有删除自己,那么代码是合法的。 If Update() does, then it is not. 如果Update()有,那么它不是。 Update() would be required to inform the calling code if it removed itself, either setting a flag or returning the next iterator (as suggested by Attila ). Update()来通知调用代码它是否自行删除,设置标志或返回下一个迭代器(如Attila所建议的那样)。

The erase function in STL usually returns an iterator to the next valid element (or end() if no such element is available). STL中的erase函数通常会将迭代器返回到下一个有效元素(如果没有这样的元素可用,则返回end() )。 You could return this iterator from Update and re-assign it to itr 您可以从Update返回此迭代器并将其重新分配给itr

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

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