Original Post
I don't have much experience with the C++ STL, so I'm incorporating it into one of my programs to learn. I'm using a vector to store a list of particles generated by a particle fountain. Each time the fountain's update function is called, the update function of each particle is called. If that function returns false (implying it is time for the particle to die), the particle should be removed from the vector: Rather simple stuff. I declare an iterator and have it point to the first particle. As long as the vector is not empty and i is not pointing to the end of the vector, I call the update function to the particle i is presently pointing to. If that returns false, I remove the particle from the vector and assign i to what it returns (which should be an iterator to the particle just after the one that was removed). If not, I advance the iterator to the next particle. However, something is not quite right. When it comes time for the first particle to die, the entire list gets wiped out. That really shouldn't happen, as each particle has a 3 second lifespan, and new particles are constantly being created, meaning as the first one dies, the one most recently born should have 3 more seconds of life. In doing some tests, I can see that each particle does in fact have a unique life span, and that when the first one does, the call to particles.erase(i) is made many times (implying that the update function is returning false for each element). That's a bit odd, as the update function is based entirely on the particles' lifespan, and again they all seem to have unique values for their time alive. From an STL standpoint, is what I'm doing there what I think I'm doing there, or are my assumptions about the iterator or the erase function off? Perhaps I should switch to a list? I'm not entirely convinced that the problem lies with the use of the vector there, but that's my present suspicion. Does anyone see anything wrong with this? I'll supply more code as needed.
bool Fountain::update(const float& seconds)
{
vector<Particle>::iterator i;
i = particles.begin();
while(!particles.empty() && i != particles.end())
{
if(!i->update(seconds))
i = particles.erase(i);
else
i++;
}
}