Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting into std::map while iterating over it?

Tags:

c++

stdmap

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?

like image 767
tschaei Avatar asked May 22 '12 16:05

tschaei


People also ask

Does map insert overwrite?

insert() doesn't overwrite - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

Does map insert invalidate iterator?

Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements. Erasing an element from a map also does not invalidate any iterators, except, of course, for iterators that actually point to the element that is being erased.

Does map in C++ maintain insertion order?

C++ hash map and hash set which preserves the order of insertion. The ordered-map library provides a hash map and a hash set which preserve the order of insertion in a way similar to Python's OrderedDict. When iterating over the map, the values will be returned in the same order as they were inserted.


2 Answers

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

like image 151
hmjd Avatar answered Sep 17 '22 17:09

hmjd


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

like image 36
Attila Avatar answered Sep 16 '22 17:09

Attila