Modifying a data structure while iterating over it

前端 未结 6 778
天涯浪人
天涯浪人 2020-12-18 18:50

What happens when you add elements to a data structure such as a vector while iterating over it. Can I not do this?

I tried this and it breaks:

int m         


        
6条回答
  •  星月不相逢
    2020-12-18 19:15

    What happens when you add elements to a data structure such as a vector while iterating over it. Can I not to this?

    The iterator would become invalid IF the vector resizes itself. So you're safe as long as the vector doesn't resize itself.

    I would suggest you to avoid this.

    The short explanation why resizing invalidates iterator:

    Initially the vector has some capacity (which you can know by calling vector::capacity().), and you add elements to it, and when it becomes full, it allocates larger size of memory, copying the elements from the old memory to the newly allocated memory, and then deletes the old memory, and the problem is that iterator still points to the old memory, which has been deallocated. That is how resizing invalidates iterator.

    Here is simple demonstration. Just see when the capacity changes:

    std::vector v;
    for(int i = 0 ; i < 100 ; i++ )
    {
      std::cout <<"size = "<
                                                            
提交回复
热议问题