0

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!

2 Answers 2

3

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; } } 
Sign up to request clarification or add additional context in comments.

5 Comments

Much appreciated, I did spend a good hour researching before posting, but didn't find too much relevant (I am quite new). Anyways Im now getting the error "vector iterators incompatible"?
@user3027864: If your compiler doesn't support C++11, then you cannot use auto that way, so continue to spell out the type.
@Veritas: What if it == begin()?!
Okay got it working, many thanks! Rather annoying I can spend so long on a single piece, and have someone else fix it in 5 minutes. But, practice makes perfect!
@user3027864: No. Learning from your mistakes makes perfect. The lesson today is to use a debugger. Be systematic, be methodical. Don't program by random guessing. I had the exact same problem when I was little and used erase for the first time, and while indeed the documentation tells you that erase invalidates the iterator, most of us don't pay attention to those things (let alone read), so we need to find out the hard way. The debugger tells you what goes wrong, and then you're burnt and will pay attention to the documentation. That process works pretty well.
0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.