std::ranges::generate
来自 cppreference.cn
定义于头文件 <algorithm> |
||
调用签名 |
||
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 比较相等。
[编辑] 复杂度
正好 ranges::distance(first, last) 次 gen() 调用和赋值。
[编辑] 可能的实现
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) |
用来自均匀随机位生成器的随机数填充一个范围 (算法函数对象) |
将连续函数调用的结果赋值给范围中的每个元素 (函数模板) |