CKTIS / C++
std::generate: fill with generator results
std::generate calls a nullary generator exactly once for every position in a range and assigns each successive result.
Version: C++23
Syntax
template<class ForwardIt, class Generator>
constexpr void std::generate(ForwardIt first, ForwardIt last, Generator gen);
template<class ExecutionPolicy, class ForwardIt, class Generator>
void std::generate(ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last, Generator gen);std::generate(first, last, gen) from <algorithm> traverses a forward-iterator range and assigns the result of a successive gen() call to every element. The no-policy overload returns void and requires at least a forward iterator. For N elements it performs exactly N generator evaluations and N assignments. std::ranges::generate accepts an input-or-output iterator and returns the ending iterator.
The example creates a four-element array and passes a lambda that advances next. Successive calls return 2, 4, 6, and 8, so the program prints 2 4 6 8 followed by a newline. State is captured by reference and is safe in this sequential call; the generator is nevertheless passed to the algorithm by value, so code should not rely on the later state of its original function object.
The range must be writable from gen() results. An exception from the generator or assignment in the no-policy overload propagates, leaving already written elements modified. With any standard ExecutionPolicy, an uncaught exception from an element access function causes std::terminate; unavailable temporary memory needed for parallelization can throw std::bad_alloc. A policy overload may copy the generator and invoke copies without order or in parallel, so a shared unsynchronized counter creates a data race. std::generate_n generates nothing when n is not positive.
Examples
#include <algorithm>
#include <array>
#include <iostream>
int main() {
std::array<int, 4> values{};
int next = 1;
std::generate(values.begin(), values.end(), [&next] {
return 2 * next++;
});
for (int value : values) std::cout << value << ' ';
std::cout << '\n';
}
Result
2 4 6 8
std::generate → 2 4 6 8