Modifying a data structure while iterating over it

前端 未结 6 761
天涯浪人
天涯浪人 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:24

    It's a bad idea in general, because if the vector is resized, the iterator will become invalid (it's wrapping a pointer into the vector's memory).

    It's also not clear what your code is really trying to do. If the iterator somehow didn't become invalid (suppose it was implemented as an index), I'd expect you to have an infinite loop there - the end would never be reached because you're always adding elements.

    Assuming you want to loop over the original elements, and add one for each, one solution would be to add the new elements to a second vector, and then concatenate that at the end:

    vector temp;
    
    // ...
    
    // Inside loop, do this:
    temp.push_back(j);
    
    // ...
    
    // After loop, do this to insert all new elements onto end of x
    x.insert(x.end(), temp.begin(), temp.end());
    

提交回复
热议问题