std::generate_n() 算法
- 自 C++20 起
- 自 C++17 起
- 自 C++11 起
- 直到 C++11
// (1)
template< class OutputIt, class Size, class Generator >
constexpr OutputIt generate_n( OutputIt first, Size count, Generator g );
// (2)
template< class ExecutionPolicy, class ForwardIt, class Size, class Generator >
ForwardIt generate_n( ExecutionPolicy&& policy, ForwardIt first,
Size count, Generator g );
// (1)
template< class OutputIt, class Size, class Generator >
OutputIt generate_n( OutputIt first, Size count, Generator g );
// (2)
template< class ExecutionPolicy, class ForwardIt, class Size, class Generator >
ForwardIt generate_n( ExecutionPolicy&& policy, ForwardIt first,
Size count, Generator g );
// (1)
template< class OutputIt, class Size, class Generator >
OutputIt generate_n( OutputIt first, Size count, Generator g );
// (1)
template< class OutputIt, class Size, class Generator >
void generate_n( OutputIt first, Size count, Generator g );
-
(1) 如果
count > 0
,则将由给定的函数对象g
生成的值赋给范围内从first
开始的前count
个元素。
否则不执行任何操作。 -
(2) 与 (1) 相同,但根据
policy
执行。
仅当 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
(直到 C++20) std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>
(自 C++20 起) 为 true
时,这些重载才参与重载解析。
参数
first | 要生成元素的范围的开始。 |
policy | 要生成的元素数量。 |
policy | 要使用的执行策略。详见执行策略。 |
g | 将被调用的生成器函数对象。 函数的签名应与以下内容等效
|
类型要求
OutputIt | LegacyOutputIterator |
ForwardIt | LegacyForwardIterator |
返回值
如果count > 0
,则为最后一个被赋值的元素的下一个迭代器,否则为 first
。 (自 C++11 起)
(无) (直到 C++11)
复杂度
g()
被调用和赋值的次数恰好为 std::max(0, count)
。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数的执行抛出异常,并且
ExecutionPolicy
是 标准策略 之一,则会调用std::terminate
。对于其他ExecutionPolicy
,行为是 实现定义的。. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
可能的实现
generate_n (1)
template<class OutputIt, class Size, class Generator>
constexpr // since C++20
OutputIt // void until C++11
generate_n(OutputIt first, Size count, Generator g)
{
for (Size i = 0; i < count; ++i, ++first)
*first = g();
return first;
}
示例
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <random>
int main()
{
std::mt19937 rng; // default constructed, seeded with fixed seed
std::generate_n(std::ostream_iterator<std::mt19937::result_type>(std::cout, " "),
5, std::ref(rng));
std::cout << '\n';
}
3499211612 581869302 3890346734 3586334585 545404204