Skip to content
C++ Basics: Find a Run of Consecutive Failures

C++ Basics: Find a Run of Consecutive Failures

November 8, 2026

Use search_n to locate consecutive repeated values rather than counting separated occurrences.

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 search-n-consecutive-failures-demo.cpp:

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

int main()
{
    const std::vector<int> status{1, 0, 1, 0, 0, 0, 1};
    const auto run = std::search_n(status.begin(), status.end(), 3, 0);
    if (run != status.end()) {
        std::cout << "three failures start at: "
                  << std::distance(status.begin(), run) << '\n';
    }
    const auto longer = std::search_n(status.begin(), status.end(), 4, 0);
    std::cout << "four consecutive: " << std::boolalpha
              << (longer != status.end()) << '\n';
}

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

g++ -std=c++20 -Wall -Wextra -Werror -pedantic search-n-consecutive-failures-demo.cpp -o search-n-consecutive-failures-demo &&
./search-n-consecutive-failures-demo

Observed output:

three failures start at: 3
four consecutive: false

Read the result

There are four zeroes in total, but only three are adjacent. The successful search returns the beginning of that run at index 3. The four-element search returns end(), which is checked before any dereference.

Apply it carefully

This algorithm searches for repetition of one value. For a multi-value pattern, use search instead. A nonpositive requested count returns the beginning of the range, so validate counts when they come from users. An end iterator is not an element and must not be dereferenced.

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 -- search-n-consecutive-failures-demo.cpp search-n-consecutive-failures-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