Dormoxx
Dormoxx

Reputation: 13

Trouble removing elements from C++ vector

I'm trying to remove 'dead' bullets from my vector of bullets. Every frame, I'm calling the Bullet::update() function which looks like this:

    void Bullet::update()
{
    for(int i = 0; i != mAmmo.size(); i++)
    {
        if(mAmmo[i].sprite.getPosition().x > 700)
            mAmmo[i].mAlive = false;
        if(mAmmo[i].mAlive == false)
        {
// I get a Debug Assertion Failed at runtime from this piece of code
            mAmmo.erase(mAmmo.begin()+i);
        }

        if(mAmmo[i].mAlive == true)
        {
            mAmmo[i].sprite.move(mMovement);
        }

    }

}

Am I doing this completely incorrectly? This is the first time I've really used vectors more than just following through a tutorial. If I need to post any more code, just tell me. I've been working on this for the past few hours, so I'm a wee bit desperate to get this to work.

Thanks in advance!

Upvotes: 1

Views: 71

Answers (1)

WhozCraig
WhozCraig

Reputation: 66194

You're easily walking into undefined behavior as soon as the ith element is the last element in your list. Use iterators, and pay special attention to the return value of erase(), as it automatically advances the iterator for you so your loop doesn't have to.

void Bullet::update()
{
    for (auto it = mAmmo.begin(); it != mAmmo.end();)
    {
        if(it->sprite.getPosition().x > 700)
            it->mAlive = false;

        if (!it->mAlive)
        {
            // erase and get next iterator
            it = mAmmo.erase(it);
        }
        else
        {   // move and increment
            it->sprite.move(mMovement);
            ++it;
        }
    }
}

Upvotes: 1

Related Questions