Iterator problem

Hi,

I am trying to make a simple text based game. Within this game I have enemies in a List and a player.

Within the code I am trying to implement where the player co-ordinates is equal to an enemy coordinate then remove the enemy from the list.

1
2
3
4
5
6
7
8
9
10
11
12
13
  for (Enemy * enemy : enemies){

   for (enemyIt = enemies.begin(); enemyIt != enemies.end(); enemyIt++)
   {
 if (enemy->getWorldLocation().getX() == playerPos->getWorldLocation().getX() && enemy->getWorldLocation().getY() == playerPos->getWorldLocation().getY())
  {
       enemies.remove(*enemyIt);
  }

 }


}


The problem being that it deletes the first enemy from the list and the one that passes the if statement.

Can anyone advise?

Last edited on
I don't understand why you are using a nested loop here. The loop variable enemy is not even used.

The remove function will search through the list and remove all elements that are equal to the passed in value. I think it should work (assuming the list doesn't contain duplicates) but it's a bit unnecessary because you already have an iterator to the element that should be removed. You probably want to use the erase function instead.

 
enemies.erase(enemyIt);

http://www.cplusplus.com/reference/list/list/erase/

Removing elements from a list while iterating can be tricky because it invalidates the iterator. This means it is not valid to keep using it (e.g. enemyIt++) after you have erased the element. The erase function returns an iterator to the next element that you can use to update the iterator, but then you also need to change the code so that you only increment the iterator if the element was not removed.

1
2
3
4
5
6
7
8
9
10
11
for (enemyIt = enemies.begin(); enemyIt != enemies.end();)
{
	if (enemy->getWorldLocation().getX() == playerPos->getWorldLocation().getX() && enemy->getWorldLocation().getY() == playerPos->getWorldLocation().getY())
	{
		enemyIt = enemies.erase(enemyIt);
	}
	else
	{
		enemyIt++;
	}
}

Last edited on
typos on the condition
1
2
3
4
if (
	(*enemyIt)->getWorldLocation().getX() == playerPos->getWorldLocation().getX()
	&& (*enemyIt)->getWorldLocation().getY() == playerPos->getWorldLocation().getY()
)

Fixed it thanks alot!
Topic archived. No new replies allowed.