在线文档教程
C++
算法 | Algorithm

std::generate

STD::生成

Defined in header
template< class ForwardIt, class Generator > void generate( ForwardIt first, ForwardIt last, Generator g (1)
template< class ExecutionPolicy, class ForwardIt, class Generator > void generate( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Generator g (2)(since C++17)

1%29分配范围内的每个元素[first, last)由给定函数对象生成的值。g...

2%29与%281%29相同,但根据policy此重载不参与过载解决,除非std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>是真的

参数

first, last-the range of elements to generate
policy-the execution policy to use. See execution policy for details.
g-generator function object that will be called. The signature of the function should be equivalent to the following: Ret fun( The type Ret must be such that an object of type ForwardIt can be dereferenced and assigned a value of type Ret. ​
Ret fun(

类型要求

---。

返回值

%280%29

复杂性

一点儿没错std::distance(first, last)调用g()还有任务。

例外

带有名为ExecutionPolicy报告错误如下:

  • 如果执行作为算法一部分调用的函数,则引发异常ExecutionPolicy是其中之一标准政策,,,std::terminate叫做。对于任何其他人ExecutionPolicy,行为是由实现定义的。

  • 如果算法不能分配内存,std::bad_alloc被扔了。

可能的实施

模板<类向前,类生成器>空生成%28 Forwardit First,Forwardit Lest,生成器g%29{而%281%21=最后%29{%2A第一++=g%28%29;}

*。

以下代码用随机数填充向量:

二次

#include <algorithm> #include <iostream> #include <vector> #include <cstdlib> int main() { std::vector<int> v(5 std::generate(v.begin(), v.end(), std::rand // Using the C function rand() std::cout << "v: "; for (auto iv: v) { std::cout << iv << " "; } std::cout << "\n"; // Initialize with default values 0,1,2,3,4 from a lambda function // Equivalent to std::iota(v.begin(), v.end(), 0 int n = {0}; std::generate(v.begin(), v.end(), [&n]{ return n++; } std::cout << "v: "; for (auto iv: v) { std::cout << iv << " "; } std::cout << "\n"; }

二次

可能的产出:

二次

v: 52894 15984720 41513563 41346135 51451456 v: 0 1 2 3 4

二次

另见

fillcopy-assigns the given value to every element in a range (function template)
generate_nassigns the results of successive function calls to N elements in a range (function template)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/Algorithm/Generate