std:: generate_n
|
定義先ヘッダ
<algorithm>
|
||
|
template
<
class
OutputIt,
class
Size,
class
Generator
>
OutputIt generate_n ( OutputIt first, Size count, Generator g ) ; |
(1) | (constexpr since C++20) |
|
template
<
class
ExecutionPolicy,
class
ForwardIt,
class
Size,
class
Generator
>
|
(2) | (since C++17) |
|
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
が
integral type
に
convertible
でない場合、プログラムは不適格となります。
目次 |
パラメータ
| first | - | 生成する要素範囲の先頭 | ||||||
| count | - | 生成する要素の数 | ||||||
| policy | - | 使用する 実行ポリシー | ||||||
| g | - |
呼び出されるジェネレータ関数オブジェクト
関数のシグネチャは以下と同等であること:
型 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; // 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
不具合報告
以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。
| DR | 適用対象 | 公開時の動作 | 正しい動作 |
|---|---|---|---|
| LWG 426 | C++98 |
計算量要件が「正確に
count
回の呼び出し
または代入」であり、 count が負の場合に破綻する |
count
が非正の場合、
呼び出しまたは代入は行われない |
| LWG 865 | C++98 |
生成範囲に続く最初の要素の位置が
返されなかった |
返される |
関連項目
|
指定された値を範囲内のN個の要素にコピー代入する
(関数テンプレート) |
|
|
連続する関数呼び出しの結果を範囲内のすべての要素に代入する
(関数テンプレート) |
|
|
(C++20)
|
関数のN回の適用結果を保存する
(アルゴリズム関数オブジェクト) |