Inserting into std::map while iterating over it?

孤街浪徒 提交于 2020-06-27 08:16:21

问题


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. It obviously doesn't work like that. Is there a way it can be done?


回答1:


From std::map::erase():

References and iterators to the erased elements are invalidated. Other references and iterators are not affected.

From std::map::insert():

No iterators or references are invalidated.

From std::map::operator[]:

No iterators or references are invalidated.

If Update() does not remove itself, then the code is legal. If Update() does, then it is not. 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).




回答2:


The erase function in STL usually returns an iterator to the next valid element (or end() if no such element is available). You could return this iterator from Update and re-assign it to itr



来源:https://stackoverflow.com/questions/10706511/inserting-into-stdmap-while-iterating-over-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!