Skip to content
C++ Basics: Copy Records While Excluding a Sentinel

C++ Basics: Copy Records While Excluding a Sentinel

November 9, 2026

Use std::remove_copy_if to create a cleaned sequence while preserving the original input for inspection.

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 1

Run the example

Save this as remove-copy-if-preserve-input-demo.cpp:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main()
{
    std::vector<int> raw{4, -1, 8, -1, 0};
    std::vector<int> clean;
    std::remove_copy_if(raw.begin(), raw.end(), std::back_inserter(clean),
                        [](int value) { return value == -1; });
    std::cout << "clean:";
    for (int value : clean) std::cout << ' ' << value;
    std::cout << '\n';
    std::cout << "raw size: " << raw.size() << '\n';
}

Compile and run it. The program runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic remove-copy-if-preserve-input-demo.cpp -o remove-copy-if-preserve-input-demo &&
./remove-copy-if-preserve-input-demo

Observed output:

clean: 4 8 0
raw size: 5

Read the result

Both -1 sentinel values are excluded, while zero is retained. The input still contains all five entries.

Apply it carefully

The predicate names what to discard, which is the opposite of copy_if. Keep source and destination storage separate; this copying algorithm is not a tool for overlapping in-place compaction. A back inserter appends and grows the vector. An ordinary output iterator instead requires enough existing destination elements. For large data, consider whether keeping both complete sequences is affordable.

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 -- remove-copy-if-preserve-input-demo.cpp remove-copy-if-preserve-input-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on