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();
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.
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.