Why i cant dereference an iterator at the end of the list?

Why this code works

1
2
3
4
5
6
Elenco e1;
e1.add(Persona("a","b"));
e1.add(Persona("c","d"));
e1.add(Persona("e","f"));
e1.add(Persona("e","f"));
e1.remove(2);   //list of 4 elements 




but this not work?
1
2
3
4
5
Elenco e1;
e1.add(Persona("a","b"));
e1.add(Persona("c","d"));
e1.add(Persona("e","f"));
e1.remove(2);   //list of 3 elements 



This is remove method
1
2
3
4
5
6
7
8
9
10
11
12
13
Persona Elenco:: remove(int pos){

	
	list<Persona> ::iterator iter=l.begin();

	for(int i=0 ;i<pos;i++){
		iter++;
	
	}

return *(l.erase(iter));      //erase ritorna un iterator 

}


Thanks in advance
From the reference material on this very site:

Return value
An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.


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

What do you think will happen when you try and dereference the end iterator?

I had change my code on this way


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Persona Elenco:: remove(int pos){

	
	list<Persona> ::iterator iter=l.begin();

	for(int i=0 ;i<pos;i++){
		iter++;
	
	}
	Persona p= *iter;
	l.erase(iter);

return p;      //erase ritorna un iterator 


}


Now it works, thanks MikeyBoy :)
Instead of using a loop you can use std::advance.

 
std::advance(iter, pos);

http://en.cppreference.com/w/cpp/iterator/advance
thanks :)
Topic archived. No new replies allowed.