in reply to Re^5: foreach to for (related to my last question)
in thread foreach to for (related to my last question)

Are you sure it's safe to add and delete items from a map while iterating over it? I personally don't know, so I'm just raising the issue.
  • Comment on Re^6: foreach to for (related to my last question)

Replies are listed 'Best First'.
Re^7: foreach to for (related to my last question)
by roboticus (Chancellor) on Jun 23, 2006 at 00:07 UTC
    ikegami:

    Good question. I'll have to check...

    Update: It appears that you're correct--it seems that deleting a map element via the iterator would potentially shuffle the map enough that the iterator would be invalid. So to do the STL conversion, we'd need a bit of an algorithm change. (Like make a stack of iterators and push the ones you want to delete on the stack, and when the loop is done, pop off the items in the stack, deleting the things they point to.

    Yecch. Probably a better way out there. But I don't know it...

    Update 2: I've done some more digging. Deleting the element invalidates the iterator doing the pointing, but doesn't invalidate other iterators. So we could use a pair of iterators, one to scan and one to delete. A bit tricky looking, so I'll leave it as an exercise to the reader.... 8^)

    I hope this is a permanent link!

    Update 3 (and last!): I found a link in a mailing list that gives this handy list:

    vector -- all vector iterators are invalidated on any change
    string & wstring -- all string iterators are invalidated on any change
    deque -- all deque iterators are invalidated on any change, except for beginning and end removals
    list -- no list iterators are invalidated, except for those referring to a deleted element
    set & multiset -- no iterators are invalidated except ones pointing to a removed element
    map & multimap -- no iterators are invalidated except ones pointed to a removed element

    --roboticus