Question

I'm writing some particle system to simulate weather. I use std::vector to store particles. When particle die (and cannot be restored) I simply erase it. So, I have function like that:

void update(float dt){
std::vector<PatriclePtr>::iterator it(particles.begin());
std::vector<PatriclePtr>::iterator end(particles.end());

    while(it!=end){
        (*it)->update(dt);

        if((*it)->isDead()){
            ParticlePtr p = (*it);
            it = particles.erase(it);
            delete p;
            p = NULL;
            continue;
        }
    }
    it++;
}

It works pretty nice. But I have some issue I don't understand. I nave some printf's which told me the address of current particle. When I erase last particle in vector then program tries update him by the way and crash. It's looks like

//--------Start updating particles------------
Update particle 11928076.
Update particle 11087264. Removed! //it's ok
Update particle 10384873.
Update particle 12764599. Removed! //last one will be crash
Update particle 12764599.
Core dumped.

It's only happend if particle 12764599 is last particle in vector. I tried find any mistake but I can't. What wrong I did?? Do You have any idea? I'm useing Fedora Linux OS and g++ . If particle can be restored it's just regenerates itself like the Doctor in her update function, so isDead return false.

Was it helpful?

Solution

I think you need to change

 while(it!=end)

to

 while(it!=particles.end())

The end is a dynamic value. It changes if you delete an element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top