1

I have a vector of structures called "Cell", which contains a position (x, y), radius, and some other variables. I need to add more cells to the end of my vector during the program execution as I loop over the vector and check a condition. Is it safe to create new cells inside the loop and add them to the vector with push_back? Or will this create memory problems as the struct is destroyed(is it?) after the loop is over? the code is more or less the following:

for (Cell c : cells) {
    if (my_condition) {
        Cell newc;
        // define cell properties
        cells.push_back(newc);
    }
}

thanks in advance

and85
  • 13
  • 4
  • 1
    Please always show a [mcve] when poting example code. In your case, it's obvious, that you can't safely change the `cells` vector while iterating through it at the same time. But in general please obey to post full compilable code, which exactly reproduces the problem you have. – πάντα ῥεῖ Feb 12 '21 at 18:49

2 Answers2

1

It's not safe as the past-end iterator will be invalidated when push_back causes the vector size to increase.

lopho
  • 177
  • 10
  • 1
    you're right, push_back breaks everything. I had to create a vector and reserve memory beforehand (with the reserve function) and then inserted the new cells into those reserved position – and85 Feb 12 '21 at 21:28
-2

It will be safe as long the Cell class correctly defines (if needed) copy and move ctors.

If Cell is a POD, it should be all fine.

SimonFarron
  • 242
  • 1
  • 4