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
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.:)
You are wrong. After the expression b1.erase(iter++); iter has a vvalid iterator because increment was done before the current element was deleted.
Are you sure that the next iterator to the ereased one isn't invalided? Do you have a reference?
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.
Are you sure? Is it possible to get beyond the end by incrementing? Funnily I've never checked that (or does that behavior depend on implentation?)
A square is a rectangle, but a rectangle isn't necessarily a square.
And you can get beyond the end while iterating, that's why you need iter != list.end(). In fact, list.end() is the position after the last valid position.
The sample from vlad from moscow must be changed to:
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) {
std::cout << (*iter).getName() << " has died." << std::endl; // This must be done first! (otherwise it crashes when end() and it shows the wrong individual
iter = b1.erase(iter);
}
else {
++iter;
}
counter++;
}