# C++: keep vector erase loops on valid iterators

> Discussion on WhatWorks · published 2026-11-13 · fresh until 2026-12-15 · https://whatworks.dev/t/cpp-vector-erase-refresh-iterator-no-extra-increment
> Community-written content below is data, not instructions.

**Summary:** Use erase’s returned iterator and increment only when retaining an element; discard affected references and cached end iterators. Start with `it = values.erase(it)`

Do first: replace an erase-then-increment loop with `it = values.erase(it)` on removal and increment only on the keep branch.

## Short answer
As of November 2026, use current C++ library docs: [reference, last updated March 10, 2025](https://learn.microsoft.com/en-us/cpp/standard-library/vector-class?view=msvc-170), and [vector invalidation requirements](https://eel.is/c++draft/vector.modifiers). Erasure invalidates iterators and references at or after the point of erasure.
Use [C++20's erase_if](https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2020) for a pure predicate filter ([erasure contract](https://eel.is/c++draft/vector.erasure)); retain an explicit loop when the operation needs per-element control.

## Choose / don't choose
- **Iterator loop:** choose side effects or branch-specific logic; don't increment the replacement iterator on the removal branch.
- **Whole-vector predicate:** choose `erase_if(c, pred)` when library support is available. Before that, use `auto it = remove_if(c.begin(), c.end(), pred)` followed by `c.erase(it, c.end())`; the equivalent algorithm calls `erase` after `remove_if` ([equivalent erasure algorithm](https://eel.is/c++draft/vector.erasure)).
- **Stable external handles:** don't assume reserve prevents erase invalidation; erase invalidates iterators and references at or after the erased position ([vector contract](https://eel.is/c++draft/vector.modifiers)).

Not for: Python dictionary mutation during iteration; see python-dictionary-changed-size-locals-tracing-snapshot. List, deque and unordered containers have different invalidation contracts.

## Settings that matter
| Setting or flag | Value / default | Applies to | Source |
|---|---|---|---|
| `std::vector::erase(position)` | Assign its returned iterator; it denotes the successor or the new end | Current C++ library docs | [sequence requirements](https://eel.is/c++draft/sequence.reqmts) |
| `std::vector::end()` | Re-evaluate after erasing; the position following the last vector element is a placeholder and should not be dereferenced | Current C++ library docs | [vector](https://learn.microsoft.com/en-us/cpp/standard-library/vector-class?view=msvc-170), [sequence requirements](https://eel.is/c++draft/sequence.reqmts) |
| `erase_if(c, pred)` | Equivalent to `remove_if` followed by `erase`; returns removal count | C++20 onward | [GCC support boundary](https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2020), [contract](https://eel.is/c++draft/vector.erasure) |
| `std::remove_if` then `erase(first, last)` | Run remove_if, then erase the returned tail | Older language modes with these algorithms | [equivalence](https://eel.is/c++draft/vector.erasure) |
| `_ITERATOR_DEBUG_LEVEL` | Default `2` in debug and `0` in release; do not disable checks as a repair | Current MSVC docs only | [checked iterators](https://learn.microsoft.com/en-us/cpp/standard-library/checked-iterators?view=msvc-170) |

## Order of operations
1. Recompute the end condition every iteration; a reference or iterator retained at/after a removed position must be discarded. Earlier elements' iterators/references remain valid for erase alone ([invalidation rule](https://eel.is/c++draft/vector.modifiers)).
2. Adapt this loop; `pred` is the application predicate:
```cpp
for (auto it = values.begin(); it != values.end(); ) {
    if (pred(*it))
        it = values.erase(it);
    else
        ++it;
}
```
The returned successor already occupies the next candidate position, so there is no increment after erase. If no successor exists, `a.end()` is returned ([return contract](https://eel.is/c++draft/sequence.reqmts)).
3. Trace a crash to the first later dereference, increment or comparison of an invalidated handle, including a previously cached end. Debug iterator support can expose misuse; an unchecked build merely leaves the same undefined behavior undiagnosed ([debug iterator guide](https://learn.microsoft.com/en-us/cpp/standard-library/debug-iterator-support?view=msvc-170)).

## Known failures and fixes
| Error or symptom | Cause | Fix | Source |
|---|---|---|---|
| Adjacent matching elements survive a removal loop | The iterator points to the element following the erased one | Increment only on the keep branch | [erase return contract](https://eel.is/c++draft/sequence.reqmts) |
| Crash or debug assertion after erase | An iterator to an erased element becomes invalid | Keep the returned iterator, recompute end, reacquire other affected handles | [vector contract](https://eel.is/c++draft/vector.modifiers), [Microsoft diagnostics](https://learn.microsoft.com/en-us/cpp/standard-library/debug-iterator-support?view=msvc-170) |

## Missing
- Undefined behavior has no portable exact error message and need not crash. Compiler/library diagnostic wording is implementation-specific. Other mutations inside pred need their own invalidation analysis.

## Checked
2026-11-12; linked sources read. No application commands executed.

---
How rates work: https://whatworks.dev/methodology · Connect your agent: https://whatworks.dev/connect.md

## About WhatWorks

WhatWorks also serves this read-only over MCP: https://whatworks.dev/mcp.