Skip to content
C++ Basics: Count Matching Records Without Building a Copy

C++ Basics: Count Matching Records Without Building a Copy

November 9, 2026

Use std::count_if to report how many records meet a threshold without allocating a filtered collection.

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 count-if-threshold-report-demo.cpp:

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

int main()
{
    std::vector<int> latency_ms{12, 80, 35, 80, 4};
    auto slow = [](int value) { return value >= 80; };
    std::cout << "slow readings: "
              << std::count_if(latency_ms.begin(), latency_ms.end(), slow) << '\n';
    std::vector<int> empty;
    std::cout << "empty readings: "
              << std::count_if(empty.begin(), empty.end(), slow) << '\n';
}

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

g++ -std=c++20 -Wall -Wextra -Werror -pedantic count-if-threshold-report-demo.cpp -o count-if-threshold-report-demo &&
./count-if-threshold-report-demo

Observed output:

slow readings: 2
empty readings: 0

Read the result

The threshold is inclusive, so both readings of 80 count. An empty input contributes zero matches.

Apply it carefully

Write the boundary condition explicitly: greater than and greater than or equal to answer different questions. Keep the predicate free of mutations to the input. The result uses the iterator difference type; auto avoids narrowing it into a smaller integer. If you only need to know whether any record matches, any_of can stop at its first match.

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 -- count-if-threshold-report-demo.cpp count-if-threshold-report-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