在迭代时插入 std::map ? [英] Inserting into std::map while iterating over it?

查看:31
本文介绍了在迭代时插入 std::map ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个地图,我像这样迭代:

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() 可能会在地图中插入一个元素,甚至从中删除一个元素,但它不一定会执行这两者中的任何一个.它显然不是那样工作的.有什么办法可以做到吗?

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?

推荐答案

来自 <代码>std::map::erase():

对已擦除元素的引用和迭代器无效.其他引用和迭代器不受影响.

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

来自 std::map::insert():

没有任何迭代器或引用无效.

No iterators or references are invalidated.

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

没有任何迭代器或引用无效.

No iterators or references are invalidated.

如果 Update() 没有删除自己,那么代码是合法的.如果 Update() 有,则不是.Update() 需要通知调用代码,如果它删除了自己,要么设置一个标志,要么返回下一个迭代器(如 阿提拉).

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).

这篇关于在迭代时插入 std::map ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆