exception:list iterator not decremental.why?

Hi.
In my code I used a list to simulate a circle and declared two iterators to traverse it.
while running,an exception appeared after eight elements was printed,stating that list iterator not decremental.
what caused this and how do i fix it?
here's my code:
#include<iostream>
#include<list>
using namespace std;
list<int> l;
int n,k,m;
int main(){
freopen("in.txt","r",stdin);
while(cin>>n>>k>>m&&n){
for(int i=1;i<=n;i++) l.push_back(i);
k%=n;
m%=n;
list<int>::iterator it1=l.begin();
list<int>::reverse_iterator it2=l.rbegin();

while(!l.empty()){
k%=l.size();
m%=l.size();
for(int j=0;j<k;j++){
it1++;
if(it1==l.end())
it1=l.begin();
}
for(int j=0;j<m;j++){
it2++;
if(it2==l.rend())
it2=l.rbegin();
}
if(*it1==*it2){
it2++;
if(it2==l.rend()) it2=l.rbegin();
l.erase(it1++);
if(it1==l.end()) it1=l.begin();
}
else{
printf("%d %d ,",*it1,*it2);
it1=l.erase(it1);
l.erase((it2++).base());
if(it1==l.end()) it1=l.begin();
if(it2==l.rend()) it2=l.rbegin();
}
}
printf("\n");
}
return 0;
}
Please use code tags.


Offhand the first problem I see is this:

l.erase(it1++);

Once you erase a node, the iterator becomes bad, so if you try to increment a bad iterator you'll have problems. The proper way to do this would be like so:

it1 = l.erase(it1);

And in fact you're doing that elsewhere in your code, which is a good thing.

This is a similar problem:

l.erase((it2++).base());

Can't increment it2 after you erase it because it2 will be bad.

The fix for this isn't as simple because it's a reverse iterator. Honestly I never really use them so I don't have a solution offhand for you. I'll let someone else field that one.

EDIT:

perhaps it's as simple as:

1
2
3
list<int>::reverse_iterator tmp = it2;
it2++;
l.erase(tmp.base());



EDIT2:

As was pointed out to me in another thread ( http://cplusplus.com/forum/beginner/24592/ ), it looks like I was mistaken. The above shouldn't be causing a problem.

Live and learn!
Last edited on
well,thanks.
but i don't think the problem is really caused by the use of l.erase((it2++).base()),because before the exception occurred this line had already been executed 4 times and nothing had happened.
even if it is the problem,I've also already tried to declare a temperate iterator to store the state of it2 before erase the element and that didn't work.
Topic archived. No new replies allowed.