STL erase

hi i'm trying to write this program section below but while it compiles normally it stops responding when i run it. Pls help me.. i can't understand what is wrong, though i believe it has to do something with the iterator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Animal{
public:
int life;
Animal(){life=0};
};

list<Animal> Mylist;
list<Animal>::iterator it;

Animal a,b,c;
Mylist.push_front(a);
Mylist.push_front(b);
Mylist.push_front(c);




for(it=MyList.begin();it != Mylist.end();it++){
                Animal p;
		p=*it;
		if(p.life<=0) it=Mylist.erase(it);
	}
}
Last edited on
There is not such fucntion as pushfront. You should use push_front member function.
oh yes! it is push_front in my code but i mispelled here. The problem remains :/
The problem is that when you do it=Mylist.erase(it); and then it++ the iterator is updated twice without checking if it != Mylist.end() in-between. If you erase the last element in the list you have skipped the end of the list so the loop will try to continue iterate over the elements after the Mylist.end(). That will most likely result in a crash.

Change you code so that it++; is only done if the element was not erased.
1
2
3
4
5
6
7
8
for(it=MyList.begin();it != Mylist.end();) { // use  while loop if you prefer
	Animal p;
	p=*it;
	if(p.life<=0) 
		it=Mylist.erase(it);
	else
		++it;
}

Thx a lot man!!! You are my hero!
Topic archived. No new replies allowed.