std:: generate
|
定义于头文件
<algorithm>
|
||
|
template
<
class
ForwardIt,
class
Generator
>
void generate ( ForwardIt first, ForwardIt last, Generator g ) ; |
(1) | (自 C++20 起为 constexpr) |
|
template
<
class
ExecutionPolicy,
class
ForwardIt,
class
Generator
>
void
generate
(
ExecutionPolicy
&&
policy,
|
(2) | (自 C++17 起) |
[
first
,
last
)
中的每个元素,赋予由给定函数对象
g
生成的值。
|
std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> 为 true 。 |
(C++20 前) |
|
std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> 为 true 。 |
(C++20 起) |
目录 |
参数
| first, last | - | 定义要生成元素范围的迭代器对 | ||||||
| policy | - | 要使用的执行策略 | ||||||
| g | - |
将被调用的生成器函数对象
函数签名应等价于以下形式:
类型 Ret 必须满足: ForwardIt 类型的对象能够被解引用并赋以 Ret 类型的值。 |
||||||
| 类型要求 | ||||||||
-
ForwardIt
必须满足
LegacyForwardIterator
的要求。
|
||||||||
复杂度
恰好 std:: distance ( first, last ) 次对 g ( ) 的调用及赋值操作。
异常
带有名为
ExecutionPolicy
模板参数的重载按以下方式报告错误:
-
如果作为算法一部分调用的函数执行抛出异常,且
ExecutionPolicy是某个 标准策略 ,则调用 std::terminate 。对于其他任何ExecutionPolicy,其行为由实现定义。 - 如果算法无法分配内存,则抛出 std::bad_alloc 。
可能的实现
template<class ForwardIt, class Generator> constexpr //< since C++20 void generate(ForwardIt first, ForwardIt last, Generator g) { for (; first != last; ++first) *first = g(); } |
示例
#include <algorithm> #include <iostream> #include <vector> void println(std::string_view fmt, const auto& v) { for (std::cout << fmt; const auto& e : v) std::cout << e << ' '; std::cout << '\n'; }; int f() { static int i; return ++i; } int main() { std::vector<int> v(5); std::generate(v.begin(), v.end(), f); println("v: ", v); // 使用lambda函数初始化默认值0,1,2,3,4 // 等效于 std::iota(v.begin(), v.end(), 0); std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; }); println("v: ", v); }
输出:
v: 1 2 3 4 5 v: 0 1 2 3 4
参见
|
将给定值复制赋值给范围内的每个元素
(函数模板) |
|
|
将连续函数调用的结果赋值给范围内的 N 个元素
(函数模板) |
|
|
(C++11)
|
用起始值的连续增量填充范围
(函数模板) |
|
(C++20)
|
将函数结果保存到范围中
(算法函数对象) |