I\'m making a game and I have a vector of bullets flying around. When the bullet is finished, I do bullets.erase(bullets.begin() + i); Then the bullet disappears. However it doe
When the bullet is finished, I do bullets.erase(bullets.begin() + i);
Don't do that. If multiple bullets are finished per frame, you get horrible performance, because the bullets that aren't finished will get copied over and over, which really isn't necessary. Here is what I would do:
#include
#include
#include
class Bullet
{
// ...
public:
bool is_finished() const;
};
int main()
{
std::vector bullets;
// ...
bullets.erase(
std::remove_if(
bullets.begin(),
bullets.end(),
std::mem_fun_ref(&Bullet::is_finished)
),
bullets.end()
);
}
This approach only moves each live bullet at most once.