Namespaces
Variants

std:: generate

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
generate
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
定义于头文件 <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,

ForwardIt first, ForwardIt last, Generator g ) ;
(2) (自 C++17 起)
1) 对范围 [ first , last ) 中的每个元素,赋予由给定函数对象 g 生成的值。
2) (1) 相同,但根据 policy 执行。
此重载仅在满足以下所有条件时参与重载决议:

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 fun ( ) ;

类型 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)
用起始值的连续增量填充范围
(函数模板)
将函数结果保存到范围中
(算法函数对象)