std::ranges::generate

Header: <algorithm>

  1. Assigns the result of successive invocations of the function object gen to each element in the range [first,last).

# Declarations

Call signature
template< std::input_or_output_iterator O, std::sentinel_for<O> S,
std::copy_constructible F >
requires std::invocable<F&> && std::indirectly_writable<O, std::invoke_result_t<F&>>
constexpr O
generate( O first, S last, F gen );

(since C++20)

template< class R, std::copy_constructible F >
requires std::invocable<F&> && ranges::output_range<R, std::invoke_result_t<F&>>
constexpr ranges::borrowed_iterator_t<R>
generate( R&& r, F gen );

(since C++20)

# Parameters

# Return value

An output iterator that compares equal to last.

# Example

#include <algorithm>
#include <array>
#include <iostream>
#include <random>
#include <string_view>
 
auto dice()
{
    static std::uniform_int_distribution<int> distr{1, 6};
    static std::random_device device;
    static std::mt19937 engine {device()};
    return distr(engine);
}
 
void iota(auto& r, int init)
{
    std::ranges::generate(r, [init] mutable { return init++; });
}
 
void print(std::string_view comment, const auto& v)
{
    for (std::cout << comment; int i : v)
        std::cout << i << ' ';
    std::cout << '\n';
}
 
int main()
{
    std::array<int, 8> v;
 
    std::ranges::generate(v.begin(), v.end(), dice);
    print("dice: ", v);
    std::ranges::generate(v, dice);
    print("dice: ", v);
 
    iota(v, 1);
    print("iota: ", v);
}

# See also