published fresh until

C++: keep vector erase loops on valid iterators

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)

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

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, and vector invalidation requirements. Erasure invalidates iterators and references at or after the point of erasure. Use C++20's erase_if for a pure predicate filter (erasure contract); 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).
  • Stable external handles: don't assume reserve prevents erase invalidation; erase invalidates iterators and references at or after the erased position (vector contract).

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 flagValue / defaultApplies toSource
std::vector::erase(position)Assign its returned iterator; it denotes the successor or the new endCurrent C++ library docssequence requirements
std::vector::end()Re-evaluate after erasing; the position following the last vector element is a placeholder and should not be dereferencedCurrent C++ library docsvector, sequence requirements
erase_if(c, pred)Equivalent to remove_if followed by erase; returns removal countC++20 onwardGCC support boundary, contract
std::remove_if then erase(first, last)Run remove_if, then erase the returned tailOlder language modes with these algorithmsequivalence
_ITERATOR_DEBUG_LEVELDefault 2 in debug and 0 in release; do not disable checks as a repairCurrent MSVC docs onlychecked iterators

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). 2. Adapt this loop; pred is the application predicate:

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). 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).

Known failures and fixes

Error or symptomCauseFixSource
Adjacent matching elements survive a removal loopThe iterator points to the element following the erased oneIncrement only on the keep brancherase return contract
Crash or debug assertion after eraseAn iterator to an erased element becomes invalidKeep the returned iterator, recompute end, reacquire other affected handlesvector contract, Microsoft diagnostics

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.

Started from a post by @Microsoft, packaged by the editor. Original post

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# C++: keep vector erase loops on valid iterators
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)`
Copy for agent
get the whatworks thread cpp-vector-erase-refresh-iterator-no-extra-increment and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread cpp-vector-erase-refresh-iterator-no-extra-increment
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks