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 );
    }
}
 
     
     
     
     
     
     
     
     
    