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以降) |
以下のいずれかの条件が満たされる場合、プログラムは不適格です。
目次 |
[edit] パラメータ
| first | - | 変更する要素の範囲の開始位置 |
| count | - | 変更する要素の数 |
| value | - | 代入される値 |
| policy | - | 使用する 実行ポリシー |
| 型要件 | ||
-OutputIt は LegacyOutputIterator の要件を満たさなければなりません。 | ||
-ForwardIt は LegacyForwardIterator の要件を満たさなければなりません。 | ||
[edit] 戻り値
0 より大きい count の場合、代入された最後の要素の次のイテレータ。それ以外の場合は first。
[edit] 計算量
正確に std::max(0, count) 回の代入。
[edit] 例外
テンプレートパラメータ ExecutionPolicy を持つオーバーロードは、次のようにエラーを報告します。
- アルゴリズムの一部として呼び出された関数の実行が例外をスローし、
ExecutionPolicyが 標準ポリシー のいずれかである場合、std::terminate が呼び出されます。その他のExecutionPolicyの場合、動作は実装定義です。 - アルゴリズムがメモリの割り当てに失敗した場合、std::bad_alloc がスローされます。
[edit] 実装例
| 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; } |
[edit] 注記
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__cpp_lib_algorithm_default_value_type |
202403 |
(C++26) | アルゴリズム (1,2) のためのリスト初期化 |
[edit] 例
#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}; // replace values of the first 5 elements with -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)
[edit] 不具合報告
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 283 | C++98 | T は CopyAssignable である必要がありましたが、T は常に OutputIt に書き込み可能ではありません。 |
代わりに書き込み可能である必要があります。 |
| LWG 426 | C++98 | 計算量の要件は「正確に count」でした。 代入ですが、これは count が負の場合に問題となります。 |
代入なし。 count が非正の場合。 |
| LWG 865 | C++98 | 代入範囲の次の要素の位置 埋め込み範囲が返されませんでした。 |
返されます |
[edit] 関連項目
| 範囲内のすべての要素に指定された値をコピー代入する (関数テンプレート) | |
| (C++20) |
指定された数の要素に値を代入する (アルゴリズム関数オブジェクト) |