std::ranges::generate_n
From cppreference.com
| Defined in header <algorithm>
|
||
| Call signature |
||
template< std::input_or_output_iterator O, std::copy_constructible F >
requires std::invocable<F&> &&
std::indirectly_writable<O, std::invoke_result_t<F&>>
constexpr O generate_n( O first, std::iter_difference_t<O> count, F gen );
|
(since C++20) | |
If count is positive, assigns the result of successive evaluations of gen() to each element in the target range [first, std::next(first, count)). Otherwise does nothing.
The function-like entities described on this page are algorithm function objects (informally known as niebloids), that is:
- Explicit template argument lists cannot be specified when calling any of them.
- None of them are visible to argument-dependent lookup.
- When any of them are found by normal unqualified lookup as the name to the left of the function-call operator, argument-dependent lookup is inhibited.
Parameters
| first | - | the beginning of the target range |
| count | - | number of elements to modify |
| gen | - | the generator function object |
Return value
The past-the-end iterator of the target range, or first if count is non-positive.
Complexity
Given \(\scriptsize N\)N as \(\scriptsize \max(\mathtt{count},0)\)max(count,0):
1) Exactly \(\scriptsize N\)N evaluations of
gen() and \(\scriptsize N\)N assignments.Possible implementation
struct generate_n_fn
{
template<std::input_or_output_iterator O, std::copy_constructible F>
requires std::invocable<F&> &&
std::indirectly_writable<O, std::invoke_result_t<F&>>
constexpr O operator()(O first, std::iter_difference_t<O> count, F gen) const
{
for (; count-- > 0; *first = std::invoke(gen), ++first)
{}
return first;
}
};
inline constexpr generate_n_fn generate_n{};
|
Example
Run this code
#include <algorithm>
#include <array>
#include <print>
#include <random>
auto dice()
{
static std::uniform_int_distribution<int> distr{1, 6};
static std::random_device engine;
static std::mt19937 noise{engine()};
return distr(noise);
}
int main()
{
std::array<int, 8> v;
std::ranges::generate_n(v.begin(), v.size(), dice);
std::print("dice: {}\n", v);
std::ranges::generate_n(v.begin(), v.size(), [n {0}] mutable { return n++; });
// same effect as std::iota(v.begin(), v.end(), 0);
std::print("iota: {}\n", v);
}
Possible output:
dice: [5, 5, 2, 2, 6, 6, 3, 5]
iota: [0, 1, 2, 3, 4, 5, 6, 7]
See also
| assigns the results of successive function calls to N elements in a range (function template) | |
(C++20) |
saves the result of a function in a range (algorithm function object) |
(C++26) |
fills a range with random numbers from a uniform random bit generator (algorithm function object) |
(C++20) |
assigns a range of elements a certain value (algorithm function object) |
(C++20) |
assigns a value to a number of elements (algorithm function object) |
(C++20) |
applies a function to a range of elements (algorithm function object) |