C++: Continue a vector loop after erasing an element
A loop that removes a record and then increments its old vector iterator can skip work or use an invalid iterator. Assign the iterator returned by erase and increment only when the current record stays.
Prepare a scratch directory
Tested on Linux with GCC 14.2.0 in C++20 mode. You need Bash, a C++20 compiler and standard library, a text editor, and the mktemp, rm, and rmdir utilities. Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save as cpp-vector-erase-next-iterator.cpp:
#include <cassert>
#include <iostream>
#include <vector>
void remove_negatives(std::vector<int>& values) {
for (auto it = values.begin(); it != values.end();) {
if (*it < 0) {
it = values.erase(it);
} else {
++it;
}
}
}
int main() {
std::vector<int> values{-1, -2, 4, -3, 5, -4};
remove_negatives(values);
assert((values == std::vector<int>{4, 5}));
std::vector<int> empty;
remove_negatives(empty);
assert(empty.empty());
std::vector<int> all_negative{-1, -2};
remove_negatives(all_negative);
assert(all_negative.empty());
std::cout << "remaining:";
for (int value : values) std::cout << ' ' << value;
std::cout << "\nall-negative size: " << all_negative.size() << '\n';
}Compile and run:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic cpp-vector-erase-next-iterator.cpp -o cpp-vector-erase-next-iterator &&
./cpp-vector-erase-next-iteratorObserved output:
remaining: 4 5
all-negative size: 0How it works
Erasing a vector element invalidates iterators and references at or after the erase position, including the previous end iterator. The returned iterator points at the following remaining element, or the new end. The loop obtains values.end() again each time.
Adjacent negative values exercise the branch that must not increment after removal. Removing the final element produces the new end, so the next condition terminates without dereferencing it. Empty input never enters the body.
Limits and choices
Repeated single-element erasure can move the tail many times and take quadratic work. For ordinary predicate filtering, the existing erase_if guide gives a more efficient whole-container operation. This loop is useful when processing requires an explicit current position and additional work between removals. Do not keep references to shifted elements across an erase or reuse a cached end iterator.
The C++ working draft specifies the library operation used here. The example uses the C++20 interface tested above; newer draft additions are outside its scope.
Clean up
rm -- cpp-vector-erase-next-iterator.cpp cpp-vector-erase-next-iterator
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect the remaining files before removing anything else.
Acknowledgements
This post was created with assistance from AI.