How to delete an element within a list

Hey there, I have just started using the in-built Lists.

I have a list of bullets for an asteroid game and can check through the list updating and drawing where needed except when I goto clear a bullet from the list (if its time remaining has run out), I get a nasty compiler error. I don't see what is wrong with my code though.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//check if current bullet in list needs to be deleted
void Ship::checkBullet()
{	
	list<Bullet>::iterator it;
	it = bulletRegister.begin();
	
	while(it != bulletRegister.end())
	{
		if (it->shouldDelete()) //check if bullet has run out of time
		{
			if (g_debugMode)
			{
				cout<<"A bullet was deleted from the bullet register. There are now "<<bulletRegister.size()<<" bullets still active\n\n";
			}
			
			bulletRegister.erase(it); //If I comment this out it works fine (obviouslly without destroying the bullet
		}
		else //if not update the position
		{
			it->updatePosition();
		}


		//check if there are any more bullets to traverse through
		if (!bulletRegister.empty())
		{
			it++;
		}
	}
}


Compiler error:
http://img833.imageshack.us/img833/1619/listfail.jpg

Any ideas? Thank you for any help
Last edited on
On line 7/27 you use 'it' no matter whether it's erased or not. Write on line 16:

it = bulletRegister.erase(it);

but then don't it++ (line 27 -> after line 20)
but surely that would cause an infinite loop as there is nothing to move it to the next iterator after checking and realising it don't need to update?


EDIT: *facepalm* I misread your answer and didn't realise you wanted me to move line 27 to just after line 20 XD

I apologise. It works perfectly now thank you.
Last edited on
Topic archived. No new replies allowed.