list::erase()

Hello again, is it possible to erase elements of a list whilst iterating through the list? , or it something you do at the end after identifying which elements you want to delete?. Below is my functions to delete specific elements of my list.

void KillMutants(list < mutantType> &tempList)

{
std::list < mutantType> ::iterator i;
for ( i = tempList.begin();
i != tempList.end();
++ i )
if( i->getAge() == 3 && i->IsMutant() ==true )
{
cout << "\nBunny " << i->getName() << " has died of old age";
i->~mutantType(); // destructor

}
}
I'm thinking i should put the erase command immediately under the ->~mutantType() ?. (If this command is needed at all?)
also,do i need to call a destructor or will the erase() command do this for me?

Appologies if I'm barking up the wrong tree again.
You don't call the destructor yourself, that will lead to a double object destruction.
See also: http://www.cplusplus.com/reference/stl/list/erase/

1
2
3
4
5
6
7
8
9
for (auto it=tempList.begin();it!=tempList.end();)
{
  if (it->getAge()==3 && it->IsMutant())
  {
    cout << "\nBunny " << it->getName() << " has died of old age";
    it=tempList.erase(it);
  }
  else ++it;
}
Last edited on
I see... I'm afraid I've got to now ask though...
Was does auto do in the 'for' statement, and why does IT need manually increasing?
When i thought the 'for' statement would take care of that?
auto is a C++0x (the next standard) "type" that basically means "make the compiler figure out the type for me".

Anyway, the reason why the for loop doesn't increment the iterator is because when you use .erase(), it will invalidate all the iterators you currently have (like the one you are looping over). erase() however returns the next valid iterator for you, so we use that instead of incrementing.
Hello again, i've been reading about the erase() command and looking at your recommendation and i'm still a little confused....In your version does the for..next control the loop until the 'if' condition is true? It's just it looks to me like the 'else' statement would be true during every loop through where the 'if' condition is not true?.

I understand what you said about the 'it' iterator invalidatingthe iterator used in IT->getAge() etc.... when it comes into play. I've also looked at the cplusplus example but that doesn't help because it doesn't show how to erase within a loop.It deletes discrete numbers in a list and then a range of numbers.

Topic archived. No new replies allowed.