Namespaces
Variants

std:: generate_n

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_n
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 OutputIt, class Size, class Generator >
OutputIt generate_n ( OutputIt first, Size count, Generator g ) ;
(1) (自 C++20 起为 constexpr)
template < class ExecutionPolicy,

class ForwardIt, class Size, class Generator >
ForwardIt generate_n ( ExecutionPolicy && policy,

ForwardIt first, Size count, Generator g ) ;
(2) (自 C++17 起)
1) count > 0 ,则将给定函数对象 g 生成的值赋给以 first 起始的范围中的前 count 个元素。否则不执行任何操作。
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 起)

如果 Size 无法 转换 整数类型 ,则程序非良构。

目录

参数

first - 待生成元素范围的起始位置
count - 要生成的元素数量
policy - 使用的 执行策略
g - 将被调用的生成器函数对象

函数签名应等价于以下形式:

Ret fun ( ) ;

类型 Ret 必须满足: OutputIt 类型的对象能够被解引用并赋以 Ret 类型的值。 ​

类型要求
-
OutputIt 必须满足 LegacyOutputIterator 的要求。
-
ForwardIt 必须满足 LegacyForwardIterator 的要求。

返回值

count > 0 则返回指向最后一个被赋值元素后一位置的迭代器,否则返回 first

复杂度

恰好 std:: max ( 0 , count ) g ( ) 的调用和赋值操作。

异常

带有名为 ExecutionPolicy 模板参数的重载按以下方式报告错误:

  • 如果作为算法一部分调用的函数执行抛出异常,且 ExecutionPolicy 是某个 标准策略 ,则调用 std::terminate 。对于其他任何 ExecutionPolicy ,其行为由实现定义。
  • 如果算法无法分配内存,则抛出 std::bad_alloc

可能的实现

template<class OutputIt, class Size, class Generator>
constexpr // 自 C++20 起
OutputIt 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; // 默认构造,使用固定种子初始化
    std::generate_n(std::ostream_iterator<std::mt19937::result_type>(std::cout, " "),
                    5, std::ref(rng));
    std::cout << '\n';
}

输出:

3499211612 581869302 3890346734 3586334585 545404204

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用标准 已发布行为 正确行为
LWG 426 C++98 复杂度要求为“恰好 count 次调用
或赋值”,当 count 为负数时存在缺陷
count 非正数时
不执行调用或赋值
LWG 865 C++98 未返回生成范围后
首个元素的位置
已返回

参见

将给定值复制赋值到范围内的 N 个元素
(函数模板)
将连续函数调用的结果赋值给范围内的每个元素
(函数模板)
保存函数 N 次调用的结果
(算法函数对象)