Jump to content
  • Advertisement
Sign in to follow this  
jchmack

list problems

This topic is 4251 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

ok i have a list of pointers to projectile objects list<projectile*> Projectiles; and i can delete the last object in the list like this


Projectiles.back()->Destroy();
delete Projectiles.back();
Projectiles.pop_back();



and it will delete the last projectile in the list perfectly fine. but when i try to remove an element thats in the middle like so:

list<projectile*>::iterator iter;

for(iter=Projectiles.begin();iter != Projectiles.end() ; iter++)
{
	if((*iter)->mBody->getAge()>5)
	{
		(*iter)->Destroy();
		delete (*iter);
		iter = Projectiles.erase(iter);
		iter--;
	}
}




i get a crash... im thinking has to be something with the way im handling iterators. Any ideas?

Share this post


Link to post
Share on other sites
Advertisement
This has been covered several times recently (and will most likely be moved to For Beginners).

Rather than offering a complete answer, I'll just try to give you a push in the right direction:
list<projectile*>::iterator iter;

for(iter=Projectiles.begin();iter != Projectiles.end() ; iter++)
{
if((*iter)->mBody->getAge()>5)
{
(*iter)->Destroy();
delete (*iter);
iter = Projectiles.erase(iter);
iter--;
}
}
1. The call to Destroy() prior to deletion is a bit of a red flag. Don't forget that the object has a destructor :)

2. What happens when the first item in the list qualifies for removal?

3. Trying to 'cancel out' the for loop updater (i.e. iter--) is a hack, more or less. Try to structure your code to eliminate this. (Remember that it's not required that all three initializing expressions be included in the 'for' statement.)

4. Look into the standard library function remove_if(), as well as the various overloads of list::erase(). Then Google 'c++ remove erase idiom'. Interestingly enough the first hit is an article right here on GDNet :)

5. You might also try Googling 'iterator pre post increment efficiency'.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!