@firedraco
Well that's incorrect. erase() invalidates the iterators so doing that won't help you as the iterator is already invalid. |
You are wrong. After the expression b1.erase(iter++); iter has a vvalid iterator because increment was done
before the current element was deleted.
@xhtmlx
The problem is that there is
two increments of the iterator in the loop. The first increment is done in the expression
b1.erase(
iter++);
and the second increment is done in the iteration statement
for(iter = b1.begin(); iter != b1.end();
++iter)
So for example if the iterator reference to the last element of the list after the first increment it will point to after the last element and then it will be increment one more that will result to memory violation.
So the loop shall be rewritten. It could be rewritten the following way
1 2 3 4 5 6 7 8 9 10 11 12
|
for(iter = b1.begin(); iter != b1.end(); /* */ ) {
(*iter).newDay();
if((*iter).getAge() > 10) {
iter = b1.erase(iter);
std::cout << (*iter).getName() << " has died." << std::endl;
}
else {
++iter;
}
counter++;
}
|
By the way I described the problem here http://cpp.forum24.ru/?1-3-40-00000003-000-0-0-1343478860
The thread is named "Why is not f( a++ ); and f( a ); a++ the same. But it is written in Russian. But I think google could help to translate the description.:)