user3027864
user3027864

Reputation: 81

Vector iterator not incremental .erase()

I am trying to delete any element of this vector that collides with player. However when I try to remove the element from the vector the program crashes and I get the error; "vector iterator not incremental".

for (std::vector<Coin>::iterator i=CoinSet.begin(); i!=CoinSet.end(); i++) 
{
    if (i->PlayerClear(player.collider()) == true)
    {
        score++;
        cout<<score<<endl;
        CoinSet.erase(i);
    }
}

This code works perfectly well until "CoinSet.erase(i)", I tried using "CoinSet.clear()" at various points, but to no avail. Any help on this would be great, thanks in advance!

Upvotes: 0

Views: 928

Answers (2)

Ozzy
Ozzy

Reputation: 64

I don't like putting ++-statements inside the argument. Therefore erase() returns an iterator that points to the next element, so one could replace the erase line with:

it = CoinSet.erase(it); // iterator is replaced with valid one

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477660

This has been discussed to death. You mustn't operate on an invalid iterator. You want something like this:

for (auto it = CoinSet.begin(); it != CoinSet.end(); /* no increment here! */ )
{
    if (/* ... */)
    {
        // ...
        CoinSet.erase(it++);
    }
    else
    {
        ++it;
    }
}

Upvotes: 3

Related Questions