Hi,
I want to remove one element pointed by iterator from a list. I read that when I use erase() on such list with precise iterator, then it returns the iterator for the element after which I removed. But now my question: is it correct not to catch what erase returns?
Example:
Code:
#include <cstdio>
#include <list>
using namespace std;
int main()
{
list<int> L;
for(int i = 0; i < 5; i++)
L.push_back(i+1);
for(list<int>::iterator i = L.begin(); i != L.end(); i++)
printf("%d\n", (*i));
printf(".\n");
for(list<int>::iterator i = L.begin(); i != L.end(); i++)
{
if((*i)==3)
printf("Hola!\n");
if((*i)==2)
{
L.erase(i); // or i=L.erase(i);
printf("%d\n", (*i));
}
}
for(list<int>::iterator i = L.begin(); i != L.end(); i++)
printf("%d\n", (*i));
return 0;
}
Becouse when there is
L.erase(i);
then printf() prints "2" but this "2" is not on the list yet... so something here is wired? But when I have i=L.erase(i); then printf() prints "3" (next element) what is correct - but then I have to do i-- not to omit one possition in the loop, right? (If I don't i-- then in the moment there will be i++ so element with "3" will be omitted in the loop - no "Hola" at the output.). Can anyone explain me that?
Regards.