std::ranges::generate_n
来自cppreference.com
在标头 <algorithm> 定义 | ||
调用签名 | ||
template<std::input_or_output_iterator O, std::copy_constructible F > requires std::invocable<F&>&&std::indirectly_writable<O, std::invoke_result_t<F&>> | (C++20 起) | |
若 0< n 则对范围 [
first,
first + n)
中的每个元素赋值连续调用函数对象 gen 的结果,否则不做任何事。
此页面上描述的函数式实体是算法函数对象(非正式地称为 niebloid),即:
目录 |
[编辑]参数
first | - | 要修改的元素范围起始 |
n | - | 要修改的元素数 |
gen | - | 生成器函数对象 |
[编辑]返回值
若 0< count 则为末元素后一位置迭代器,否则为 first。
[编辑]复杂度
准确调用 n 次 gen() 以及赋值。
[编辑]可能的实现
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> n, F gen)const{for(; n-->0;*first =std::invoke(gen), ++first){}return first;}}; inlineconstexpr generate_n_fn generate_n {}; |
[编辑]示例
运行此代码
#include <algorithm>#include <array>#include <iostream>#include <random>#include <string_view> auto dice(){staticstd::uniform_int_distribution<int> distr {1, 6};staticstd::random_device engine;staticstd::mt19937 noise {engine()};return distr(noise);} void print(constauto& v, std::string_view comment){for(int i : v)std::cout<< i <<' ';std::cout<<'('<< comment <<")\n";} int main(){std::array<int, 8> v; std::ranges::generate_n(v.begin(), v.size(), dice); print(v, "dice"); std::ranges::generate_n(v.begin(), v.size(), [n {0}] mutable {return n++;});// same effect as std::iota(v.begin(), v.end(), 0); print(v, "iota");}
可能的输出:
5 5 2 2 6 6 3 5 (dice) 0 1 2 3 4 5 6 7 (iota)
[编辑]参阅
(C++20) | 将函数结果保存到范围中 (算法函数对象) |
(C++26) | 用来自均匀随机位发生器的随机数填充范围 (算法函数对象) |
(C++20) | 赋给定值到范围中元素 (算法函数对象) |
(C++20) | 赋给定值到若干元素 (算法函数对象) |
(C++20) | 应用函数到元素范围 (算法函数对象) |
赋连续函数调用结果到范围中 N 个元素 (函数模板) |