C++ Basics: Remove Forward-List Nodes Without Skipping Matches
Track the preceding node when removing matching elements from a singly linked forward_list.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
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 this as forward-list-erase-after-demo.cpp:
#include <forward_list>
#include <iostream>
int main()
{
std::forward_list<int> values{0, 0, 3, 0, 5, 0};
auto previous = values.before_begin();
auto current = values.begin();
while (current != values.end()) {
if (*current == 0) {
current = values.erase_after(previous);
} else {
previous = current;
++current;
}
}
std::cout << "remaining:";
for (int value : values) std::cout << ' ' << value;
std::cout << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic forward-list-erase-after-demo.cpp -o forward-list-erase-after-demo &&
./forward-list-erase-after-demoObserved output:
remaining: 3 5Read the result
Both leading zeroes, the interior zero and the trailing zero disappear. After an erasure, previous stays put and erase_after returns the next candidate. Advancing previous after deleting would skip consecutive matches.
Apply it carefully
before_begin() is a position before the first node; never dereference it. erase_after requires a following element, which the loop establishes through current != end(). Erasing invalidates the erased element only. For a simple predicate without extra bookkeeping, the container’s remove_if member is shorter.
The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- forward-list-erase-after-demo.cpp forward-list-erase-after-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.