List iterator not incrementable, enhanced for loop

Jan 3, 2015 at 4:28pm
I am trying to fiddle with lists and the .remove, but when it removes something it crashes the program. Searching google the error happens when the iterator goes outside the valid spectrum, and they give help to solve it. But i havent found how to do it with the enhanced for loop?

1
2
3
4
5
  for (auto&& b : bullets){ 
		if (!b->alive) 
			bullets.remove(b); 	
	}
}
Jan 3, 2015 at 10:24pm
I don't know your bullets type. But usually an iterators code depends on an unmodified container. Restart the iterator after modifying the container. Try something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
bool restartIt(false);
do
{
    for (auto&& b : bullets)
    {
        if (!b->alive)
        {
            bullets.remove(b);
            restartIt = true;
            break;
        }
    }
} while (restartIt);
Topic archived. No new replies allowed.