PeppeJ
PeppeJ

Reputation: 643

vector::empty() bugged, or am I missing something?

I've got this piece of code, which throws an out-of-range error.

if (!_enemyVec.empty())
    {
        for (std::vector<EnemyShip*>::size_type i = 0; i != _enemyVec.size(); i++)
        {
            if (!_projVec.empty())
            {
                for (std::vector<Projectile*>::size_type y = 0; y != _projVec.size(); y++)
                {
                    ===>_projVec[y]->CheckCollision(_enemyVec[i]);
                    if (_projVec[y]->Destroy())
                        DestroyProj(y);
                    if (_enemyVec[i]->Destroy())
                        DestroyShip(i);
                }
            }
        }
    }

Notice how I've got if (!_projVec.empty()) which should be "false" if the vector _projVec is empty.

The "===>" is where I get my out-of-range error(since _projVec is empty).

According to http://www.cplusplus.com/reference/vector/vector/empty/ vector::empty "Returns whether the vector is empty (i.e. whether its size is 0)."

However when I run the code it goes into the 2nd for-loop throwing an out-of-range error, while my vector is empty (it's size is 0)?

+       _projVec    { size=0 }  std::vector<Projectile *,std::allocator<Projectile *> >

I think I'm missing something so I'm wondering if anyone here can clear this up?

EDIT: Here are my DestroyProj/Ship functions.

void ObjectManager::DestroyShip(std::vector<EnemyShip*>::size_type &index)
{
    delete _enemyVec[index];
    _enemyVec[index] = nullptr;
    _enemyVec.erase(_enemyVec.begin() + index);
    index--;
    AddScore(10);
}

void ObjectManager::DestroyProj(std::vector<Projectile*>::size_type &index)
{
    delete _projVec[index];
    _projVec[index] = nullptr;
    _projVec.erase(_projVec.begin() + index);
    index--;
}

As BWG pointed out, it shouldn't iterate if they are empty from the beginning, so the problem probably lies where I set the index back once. I also realise that this is probably a bad way to iterate through the vectors, so if someone can suggest me a different way to do it would be very much appreciated.

Please note that during this nested for-loop I want to be able to remove an item from both vectors.

Upvotes: 0

Views: 181

Answers (3)

moswald
moswald

Reputation: 11667

You should iterate over a copy of the vectors, or you should remember which indexes to remove and then remove them at the end. Don't let DestroyProj and DestroyShip modify the vector.

Upvotes: 0

user2249683
user2249683

Reputation:

You have two nested loops modifying two vectors. While erasing from the inner vector is fine, erasing an element from the outer vector, is not (assume the outer has one element, only)

Upvotes: 3

sth
sth

Reputation: 229573

Probably DestroyProj() (or one of the other functions) modifies _projVec. So even if it wasn't empty at the start of the loop, it might become empty when projects are removed.

Upvotes: 1

Related Questions