C++ Basics: Generate Values with Local Callable State
Use std::generate_n to append a short sequence whose next value depends on local state. An insertion iterator grows the destination as values arrive.
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 generate-n-stateful-sequence-demo.cpp:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> codes;
auto next_code = [next = 100]() mutable { return next++; };
std::generate_n(std::back_inserter(codes), 3, next_code);
std::cout << "codes:";
for (int code : codes) std::cout << ' ' << code;
std::cout << '\n';
std::cout << "original callable: " << next_code() << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic generate-n-stateful-sequence-demo.cpp -o generate-n-stateful-sequence-demo &&
./generate-n-stateful-sequence-demoObserved output:
codes: 100 101 102
original callable: 100Read the result
The appended values are 100, 101 and 102. The separate call still returns 100 because the algorithm takes the callable by value; its internal copy consumed the sequence.
Apply it carefully
Do not use the caller-owned callable to infer how far an algorithm advanced its copy. Capture external state by reference only when that sharing is deliberate and its lifetime covers the call. This example uses the ordinary sequential overload. Keep generated arithmetic representable and cap counts before allocating large amounts of memory.
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 -- generate-n-stateful-sequence-demo.cpp generate-n-stateful-sequence-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.