简体   繁体   中英

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!

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;
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM