std::ranges::generate
来自 cppreference.cn
定义于头文件 <algorithm> |
||
调用签名 (Call signature) |
||
template< std::input_or_output_iterator O, std::sentinel_for<O> S, std::copy_constructible F > |
(1) | (C++20 起) |
template< class R, std::copy_constructible F > requires std::invocable<F&> && ranges::output_range<R, std::invoke_result_t<F&>> |
(2) | (C++20 起) |
1) 将函数对象 gen 的连续调用结果赋值给范围
[
first,
last)
中的每个元素。本页描述的类函数实体是 算法函数对象(非正式地称为 niebloids),即
目录 |
[编辑] 参数
first, last | - | 定义要修改的元素范围的迭代器-哨兵对 |
r | - | 要修改的元素范围 |
gen | - | 生成器函数对象 |
[编辑] 返回值
一个与 last 比较相等的输出迭代器。
[编辑] 复杂度
对 gen() 的调用和赋值操作的次数精确地为 ranges::distance(first, last)。
[编辑] 可能的实现
struct generate_fn { 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 operator()(O first, S last, F gen) const { for (; first != last; *first = std::invoke(gen), ++first) {} return first; } 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> operator()(R&& r, F gen) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(gen)); } }; inline constexpr generate_fn generate {}; |
[编辑] 示例
运行此代码
#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); }
可能的输出
dice: 4 3 1 6 6 4 5 5 dice: 4 2 5 3 6 2 6 2 iota: 1 2 3 4 5 6 7 8
[编辑] 参阅
(C++20) |
保存 N 次应用一个函数的结果 (算法函数对象) |
(C++20) |
给一个范围的元素赋某个值 (算法函数对象) |
(C++20) |
给一定数量的元素赋一个值 (算法函数对象) |
(C++20) |
对一个范围的元素应用函数 (算法函数对象) |
(C++26) |
用来自均匀随机位生成器的随机数填充范围 (算法函数对象) |
将连续函数调用的结果赋给一个范围中的每个元素 (函数模板) |