Jump to content

  • Log In with Google      Sign In   
  • Create Account


#ActualMercile55

Posted 21 January 2013 - 05:15 PM

I knew I should've tested the snippets before posting them. laugh.png

So the correct method to 'swap and pop' is:
std::vector<Zombie> zombies;typedef d::vector<Zombie>::iterator ZombieIterator; for(ZombieIterator it = zombies.begin(); it != zombies.end();){	if(it->dead)	{		//Swap the value of the current zombie with the zombie at the back of the container.		std::swap(*it, zombies.back());		//Pop the back of the container.		zombies.pop_back();	}	else	{		++it;	}}
Looking over my previous version, it'd also skip whatever elements were at the end before being swapped. rolleyes.gif

But the correct choice in most cases is the third solution I posted, using the heavily optimized and standardized std::remove_if() algorithm.
This isn't right man, try this when all Zombies are dead, and you'll end up with a crash, as when you pop_back the very first element, the iterator becomes invalid. It will be ok, as long as there's at least one element left though.
It's always good idea to make sure what does and what doesn't invalidate your iterator, and avoid any such cases if possible. It saves time in the future.

remove_if() does the trick for most cases, although it may not be as fast, due to additional calls overhead.

#1Mercile55

Posted 21 January 2013 - 05:13 PM

I knew I should've tested the snippets before posting them. laugh.png
 
So the correct method to 'swap and pop' is:
std::vector<Zombie> zombies;
typedef d::vector<Zombie>::iterator ZombieIterator;
 
for(ZombieIterator it = zombies.begin(); it != zombies.end();)
{
	if(it->dead)
	{
		//Swap the value of the current zombie with the zombie at the back of the container.
		std::swap(*it, zombies.back());
		//Pop the back of the container.
		zombies.pop_back();
	}
	else
	{
		++it;
	}
}

Looking over my previous version, it'd also skip whatever elements were at the end before being swapped. rolleyes.gif

 

But the correct choice in most cases is the third solution I posted, using the heavily optimized and standardized std::remove_if() algorithm.

 

This isn't right man, try this when all Zombies are dead, and you'll end up with a crash, as when you pop_back the very first element, the iterator becomes invalid. It will be ok, as long as there's at least one element left though.

It's always good idea to make sure what does and what doesn't invalidate your iterator, and avoid any such cases if possible. It saves time in the future.


PARTNERS