But eventually, you still don't want to store a lot of dead objects. Especially in bigger projects, where processing speed and memory usage might become a bottleneck, you want to minimize the amount of active objects.
Don't iterate with indices, unless you really need the random access. For iteration, you should use iterators:
for (auto itr = sprites.begin(); itr != sprites.end(); ++itr)
doSomething(*itr);
or the range-based for loop:
for (sf::Sprite& sprite : sprites)
doSomething(sprite);
To erase an element during iteration, you can use
erase() and assign its return value:
for (auto itr = sprites.begin(); itr != sprites.end(); )
{
doSomething(*itr);
if (isDead(*itr))
itr = sprites.erase(itr);
else
++itr;
}
However, for
std::vector this is very inefficient, since
erase() moves all the following elements. In general, you should therefore stick to the STL algorithms
std::remove() and
std::remove_if(). This is also called the "erase-remove idiom".
auto firstToRemove = std::remove_if(sprites.begin(), sprites.end(), &isDead);
sprites.erase(firstToRemove, sprites.end());
Consult
www.cppreference.com for detailed information on the STL.