Skip to content
C++ Basics: Normalize Invalid Entries in Place

C++ Basics: Normalize Invalid Entries in Place

November 9, 2026

Use std::replace_if to substitute a fixed value for matching entries while keeping the sequence length and positions unchanged.

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 replace-if-sentinel-normalization-demo.cpp:

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

int main()
{
    std::vector<int> counts{3, -1, 0, -9, 5};
    std::replace_if(counts.begin(), counts.end(),
                    [](int value) { return value < 0; }, 0);
    std::cout << "counts:";
    for (int count : counts) std::cout << ' ' << count;
    std::cout << '\n';
    std::cout << "size: " << counts.size() << '\n';
}

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

g++ -std=c++20 -Wall -Wextra -Werror -pedantic replace-if-sentinel-normalization-demo.cpp -o replace-if-sentinel-normalization-demo &&
./replace-if-sentinel-normalization-demo

Observed output:

counts: 3 0 0 0 5
size: 5

Read the result

The two negative values become zero. The existing zero stays in place, and the vector still has five elements.

Apply it carefully

Replacing a sentinel can lose information: after normalization, genuine zeros and formerly invalid readings are indistinguishable. Preserve a separate validity field when that distinction matters. The replacement is the same for every match; use transform for a computed replacement. Pass a stable replacement value rather than a reference to an element that the operation itself may overwrite.

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 -- replace-if-sentinel-normalization-demo.cpp replace-if-sentinel-normalization-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