Why i cant dereference an iterator at the end of the list?
Apr 8, 2014 at 9:46am UTC
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
Apr 8, 2014 at 9:51am UTC
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?
Apr 8, 2014 at 2:05pm UTC
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 :)
Apr 8, 2014 at 2:10pm UTC
Apr 9, 2014 at 8:12am UTC
thanks :)
Topic archived. No new replies allowed.