Do STL iterators guarantee validity after collection was changed?

前端 未结 3 432
南方客
南方客 2020-12-01 07:49

Let\'s say I have some kind of collection and I obtained an iterator for the beginning of it. Now let\'s say I modified the collection. Can I still use the iterator safely,

3条回答
  •  隐瞒了意图╮
    2020-12-01 08:18

    That depends on the collection in question. Just for example, modifying a std::vector (e.g., adding an element somewhere) can invalidate all iterators into that vector. By contrast, with a std::list, iterators remain valid when you add another element to the list. In some cases, the rules are even more complex (e.g., if memory serves, with a std::deque, adding to the beginning or end leaves existing iterators valid, but adding anywhere else can invalidate them -- but my memory is sufficiently poor that you should check before depending on that).

提交回复
热议问题