std::ranges::generate_n
来自 cppreference.cn
定义于头文件 <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,则将连续调用函数对象 gen 的结果赋值给范围 [
first,
first + n)
中的每个元素。 否则不执行任何操作。
此页面上描述的类函数实体是算法函数对象(非正式地称为 niebloids),即
内容 |
[编辑] 参数
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; } }; inline constexpr generate_n_fn generate_n {}; |
[编辑] 示例
运行此代码
#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 engine; static std::mt19937 noise {engine()}; return distr(noise); } void print(const auto& 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 个元素 (函数模板) |