Try this instead:
for (it=sList.begin(); it != sList.end(); it++)
{
for (it2=sList.end()-1; it2 != it+1; it2--)
{
if ((*it) == (*it2))
{
it = sList.erase(it, it2)-1;
break;
}
}
}
This new version avoids two errors in the original version of the code. First, the code now properly handles the edge conditions of the inner for loop. In the original code, the for loop allowed it2
to go up to sList.end()-1
, but then the next line incremented it to sList.end()
on the last iteration. The next line then dereferenced this (invalid) iterator which is one past the last value of the list (because that's what end
returns, it's not an iterator to the last value of the list).
Second, calling erase
invalidates any iterators pointing to any of the values erased (which in this case would including any iterators from it
to it2-1
). By starting at the end of the list and working our way forward, we no longer have to continue iterating when we find the value, and can break
from the inner loop once we find it. erase
returns an iterator to the next element in the list after the elements deleted (which would be the next element we want to try for it
). But since the for loop increments it
, we subtract 1 from what's returned by erase
so that it
points to the right element once it's incremented at the beginning of the next loop iteration. (Note that in the case that it
points to the first element, we actually temporarily set it to point an element before the beginning of the list; however, this is only temporary and we don't dereference the iterator while it's pointing outside the list).
Note that this preserves the original behavior of the code for the case 0 2 3 4 5 1 6 7 8 0 9 10 11 1
. You haven't explicitly stated what order the deletes should occur (should the elements between 0
's be erased first, or the elements between 1
's, or do we need to add additional logic to actually erase the whole range except for the first 0
and 1
?), but this code behaves like the original and erases the numbers in between the 0
's and ignores the fact that the 9 10 11
afterwards was original in between matching 1
's.