C++ Basics: Reset Only the Used Prefix of a Buffer
Use std::fill_n when a buffer has a known number of entries to reset. The returned iterator marks the end of the written prefix.
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 1Run the example
Save this as fill-n-prefix-reset-demo.cpp:
#include <algorithm>
#include <array>
#include <iostream>
int main()
{
std::array<int, 5> slots{9, 9, 9, 9, 9};
auto next = std::fill_n(slots.begin(), 3, 0);
std::cout << "next index: " << next - slots.begin() << '\n';
std::cout << "slots:";
for (int value : slots) std::cout << ' ' << value;
std::cout << '\n';
auto unchanged = std::fill_n(slots.begin(), 0, 7);
std::cout << "zero count index: " << unchanged - slots.begin() << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic fill-n-prefix-reset-demo.cpp -o fill-n-prefix-reset-demo &&
./fill-n-prefix-reset-demoObserved output:
next index: 3
slots: 0 0 0 9 9
zero count index: 0Read the result
Only the first three entries become zero. The returned iterator points at index 3, and a zero count returns the original iterator without writing.
Apply it carefully
The destination must have room for every assignment. A count does not perform a bounds check or grow a container. For a count received from outside the program, validate that it is nonnegative and no larger than the available prefix before calling fill_n. Use fill over a whole range when every entry should change.
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 -- fill-n-prefix-reset-demo.cpp fill-n-prefix-reset-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.