Delete and add elements to vector inside main loop
c++, openframeworks, vector
Solution
Every time you insert in to a `vector`, the iterators to it are potentially invalidated. You cannot do this:
if ( ofRandom(1) < .1 ) addSomeNewOnes();
it++
Because after the call to `addSomeNewOnes()`, `it` is invalid.
You can use the iterator returned by a call to `vector::insert`, but in your case that would mean re-engineering your code.
This is something you might want to do, anyway, as your code is a bit kludgy.
Problem
I searched before but couldn't find any answers. I am somewhat new to c++, so hopefully this question won't be too stupid. I am trying to add and remove elements in a vector, in my case populated with particles during a big update or drawing loop over all particles. For example remove some particles because they died, but also add a few other ones because one particle collided with an object and I want to show a small particle burst at the point of collision. I made this simple test code in a demo file to get to the bottom of the problem. I think the problem is since I delete and add particles the iterator pointer becomes invalid. Deletion works, but when I add a few random ones I get a null pointer. the code below is somewhat verbose, I know I should use iterators with begin() and end() but I had the same problem with those, and played with the code a bit, trying more javascript array style looping because I am more familiar with that. ``` void testApp::drawParticles() { int i=0; int max = particles.size(); vector<Particle*>::iterator it = particles.begin(); while ( i < max ) { Particle * p = particles[i]; if ( ofRandom(1) > .9 ) { it = particles.erase(it); max = particles.size(); } else { ofSetColor(255, 255, 0); ofCircle( p->x, p->y, p->z, 10); if ( ofRandom(1) < .1 ) addSomeNewOnes(); i++; it++; } } } void testApp::addSomeNewOnes() { int max = ofRandom(4); for ( int i=0; i<max; i++ ) { Particle * p = new Particle(); p->x = ofRandom( -ofGetWidth()/2, ofGetWidth()/2 ); p->y = ofRandom( -ofGetHeight()/2, ofGetHeight()/2 ); p->z = ofRandom( -ofGetHeight()/2, ofGetHeight()/2 ); particles.push_back( p ); } } ```