Modifying a data structure while iterating over it

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

    Iterators are invalidated by some operations that modify a std::vector.

    Other containers have various rules about when iterators are and are not invalidated. This is a post (by yours truly) with details.

    By the way, the entrypoint function main() MUST return int:

    int main() { ... }
    

提交回复
热议问题