Infinite for loop deleting elements from list

I get a infinite loop when deleting elements that are odd in a list. At first I thought the list functions were returning new values from function end and begin so I made them constants outside the loop but get the same result. If I remove my list function erase and loop thru elements checking if they are odd or even everything works.

1
2
3
4
5
6
7
8
9
10
11
12
  list<int> even = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };

    for(list<int>::iterator x = even.begin(); x != even.end(); ++x){
        cout << "Number being tested: " << *x << endl << "Result: ";
        if((*x % 2) != 0){
            even.erase(x); //comment out this line and loop functions correctly displaying which numbers found odd or even
            cout << "Odd" << endl << "Number has been deleted" << endl << endl;
            }
        else
            cout << "Even" << endl << endl;
        }
Last edited on
ok, solved it myself, I am making a out of range loop because the erase function increments my iterator each time I delete the element it points to. To make my loop function correctly, I must only increment the iterator if I do not call the erase function like below. Hope this helps someone in the future. However does anyone know why I dont get the same behavior with a vector? Code below works fine...

1
2
3
4
5
6
7
8
9
list<int> even = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };

list<int>::iterator lend = even.end(), beg = even.begin();
    while(beg != lend){
        if((*beg % 2) != 0)
            beg = even.erase(beg);
            else
            ++beg;
        }


Why is this ok?

1
2
3
4
vector<int> even = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };
for(vector<int>::iterator i = even.begin(); i != even.end();++i)
        if((*i % 2) != 0)
            odd.erase(i);
Last edited on
Topic archived. No new replies allowed.