C++ Basics: Erase the Last Matching Value through a Reverse Iterator
Translate a reverse search result into the forward iterator required by vector::erase.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need 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 reverse-iterator-erase-demo.cpp:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> values{1, 2, 3, 2, 4};
const auto found = std::find(values.rbegin(), values.rend(), 2);
if (found != values.rend()) {
values.erase(std::prev(found.base()));
}
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 reverse-iterator-erase-demo.cpp -o reverse-iterator-erase-demo &&
./reverse-iterator-erase-demoObserved output:
Remaining: 1 2 3 4Read the result
The reverse search locates the final 2 in forward order. base() points one position after the element represented by a reverse iterator, so prev(base()) selects the actual element to erase. The earlier 2 remains.
Apply it carefully
Check against rend() first. Calling prev() on the base of rend() would step before begin(). Passing found.base() directly to erase would remove the wrong value or pass end(). Vector erasure invalidates iterators and references at or after the erased position, including this reverse search result; do not reuse it after the mutation.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- reverse-iterator-erase-demo.cpp reverse-iterator-erase-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.