advanced patterns of std::vector with custom objects in C++20 when resizing during iteration
I just started working with I'm following best practices but I'm sure I'm missing something obvious here, but I'm working with unexpected behavior when resizing a `std::vector` of custom objects in C++20 while iterating through it. I have a class `MyObject` which contains some data and a method to display its contents: ```cpp class MyObject { public: MyObject(int value) : value(value) {} void display() const { std::cout << value << '\n'; } private: int value; }; ``` I created a vector to hold these objects and implemented the following code to iterate through the vector: ```cpp std::vector<MyObject> myObjects; for (int i = 0; i < 5; ++i) { myObjects.emplace_back(i); } for (size_t i = 0; i < myObjects.size(); ++i) { myObjects[i].display(); if (i == 2) { myObjects.resize(myObjects.size() + 2); // Resize during iteration } } ``` After running this code, I noticed that the program sometimes crashes or displays corrupted values. The expected output should be the integers from 0 to 4, but I get inconsistent results or a segmentation fault when I resize the vector. I have tried using a range-based for loop and `std::vector::reserve()` before adding elements, but the behavior remains the same. I suspect that resizing the vector invalidates the iterators or the indices, but I need confirmation on this. What is the best practice for resizing a vector during iteration? Should I be handling the iteration differently to avoid this scenario? Any help would be appreciated! What am I doing wrong? This is part of a larger API I'm building. I've been using Cpp for about a year now. Could someone point me to the right documentation? My team is using Cpp for this service. Thanks in advance! I'm working in a CentOS environment. I'd love to hear your thoughts on this.