std:: fill_n
|
ヘッダーで定義
<algorithm>
|
||
| (1) | ||
|
template
<
class
OutputIt,
class
Size,
class
T
>
OutputIt fill_n ( OutputIt first, Size count, const T & value ) ; |
(C++20以降constexpr)
(C++26まで) |
|
|
template
<
class
OutputIt,
class
Size,
class
T
=
typename
std::
iterator_traits
|
(C++26以降) | |
| (2) | ||
|
template
<
class
ExecutionPolicy,
class
ForwardIt,
class
Size,
class
T
>
|
(C++17以降)
(C++26まで) |
|
|
template
<
class
ExecutionPolicy,
class
ForwardIt,
class
Size,
|
(C++26以降) | |
|
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 | - | 変更する要素範囲の先頭 |
| count | - | 変更する要素の数 |
| value | - | 代入する値 |
| policy | - | 使用する 実行ポリシー |
| 型要件 | ||
-
OutputIt
は
LegacyOutputIterator
の要件を満たさなければならない
|
||
-
ForwardIt
は
LegacyForwardIterator
の要件を満たさなければならない
|
||
戻り値
count > 0 の場合、代入された最後の要素の次を指すイテレータ、 first の場合、それ以外。
計算量
正確に std:: max ( 0 , count ) 回の代入。
例外
ExecutionPolicy
という名前のテンプレートパラメータを持つオーバーロードは、
以下のようにエラーを報告します:
-
アルゴリズムの一部として呼び出された関数の実行が例外をスローした場合、
ExecutionPolicyが 標準ポリシー のいずれかであるとき、 std::terminate が呼び出されます。それ以外のExecutionPolicyについては、動作は実装定義です。 - アルゴリズムがメモリの確保に失敗した場合、 std::bad_alloc がスローされます。
実装例
| fill_n |
|---|
template<class OutputIt, class Size, class T = typename std::iterator_traits<OutputIt>::value_type> OutputIt fill_n(OutputIt first, Size count, const T& value) { for (Size i = 0; i < count; i++) *first++ = value; return first; } |
`タグ内)は翻訳せず保持 - テキスト部分のみ日本語に翻訳 - C++専門用語は翻訳せず保持
注記
| 機能テスト マクロ | 値 | 標準 | 機能 |
|---|---|---|---|
__cpp_lib_algorithm_default_value_type
|
202403
|
(C++26) | リスト初期化 アルゴリズム用 ( 1,2 ) |
例
#include <algorithm> #include <complex> #include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> v1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // 最初の5要素の値を-1で置換 std::fill_n(v1.begin(), 5, -1); std::copy_n(v1.cbegin(), v1.size(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; std::vector<std::complex<double>> nums{{1, 3}, {2, 2}, {4, 8}}; #ifdef __cpp_lib_algorithm_default_value_type std::fill_n(nums.begin(), 2, {4, 2}); #else std::fill_n(nums.begin(), 2, std::complex<double>{4, 2}); #endif std::copy_n(nums.cbegin(), nums.size(), std::ostream_iterator<std::complex<double>>(std::cout, " ")); std::cout << '\n'; }
出力:
-1 -1 -1 -1 -1 5 6 7 8 9 (4,2) (4,2) (4,8)
不具合報告
以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。
| DR | 適用対象 | 公開時の動作 | 正しい動作 |
|---|---|---|---|
| LWG 283 | C++98 |
T
は
CopyAssignable
であることが要求されていたが、
T
が常に
OutputIt
に書き込み可能とは限らない
|
書き込み可能であることが要求される |
| LWG 426 | C++98 |
計算量要件が「正確に
count
回の代入」であり、 count が負の場合に破綻する |
count が非正の場合は代入を行わない |
| LWG 865 | C++98 |
埋め込み範囲に続く最初の要素の位置が
返されなかった |
返される |
関連項目
|
指定された値を範囲内の全要素にコピー代入する
(関数テンプレート) |
|
|
(C++20)
|
指定された個数の要素に値を代入する
(アルゴリズム関数オブジェクト) |