MiddleDebuggingVery commonNot answered yet
Why is erasing in this loop undefined behavior?
This loop tries to drop even numbers from a vector, but crashes or skips elements.
std::vector<int> v{1, 2, 3, 4, 5};
for (auto it = v.begin(); it != v.end(); ++it) {
if (*it % 2 == 0) v.erase(it);
}
Find and fix the bug.
vector::erase invalidates it and every iterator after it; the next ++it then advances a dangling iterator — UB. Fix: use the return value, it = v.erase(it);, and only ++it when you did not erase. Or std::erase_if(v, pred); (C++20).
- ✗Believing erase leaves the iterator pointing at the next element
- ✗Blaming repeated end() calls instead of iterator invalidation
- ✗Thinking the erase-remove idiom is unnecessary here
- →How does the erase-remove idiom avoid this problem entirely?
- →Which containers do NOT invalidate other iterators on erase?