std::fill_n
提供: cppreference.com
ヘッダ <algorithm> で定義 | ||
(1) | ||
template<class OutputIt, class Size, class T > void fill_n( OutputIt first, Size count, const T& value ); | (C++11未満) | |
template<class OutputIt, class Size, class T > OutputIt fill_n( OutputIt first, Size count, const T& value ); | (C++11以上) (C++20未満) | |
template<class OutputIt, class Size, class T > constexpr OutputIt fill_n( OutputIt first, Size count, const T& value ); | (C++20以上) | |
template<class ExecutionPolicy, class ForwardIt, class Size, class T > ForwardIt fill_n( ExecutionPolicy&& policy, ForwardIt first, Size count, const T& value ); | (2) | (C++17以上) |
1)
count > 0
の場合は、指定された value
を first
から始まる範囲の先頭 count
個の要素に代入します。 そうでなければ、何もしません。2)(1) と同じですが、
policy
に従って実行されます。 このオーバーロードは、 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> が true である場合にのみ、オーバーロード解決に参加します目次 |
[編集]引数
first | - | 変更する要素の範囲の先頭 |
count | - | 変更する要素の数 |
value | - | 代入する値 |
policy | - | 使用する実行ポリシー。 詳細は実行ポリシーを参照してください |
型の要件 | ||
-OutputIt は LegacyOutputIterator の要件を満たさなければなりません。 | ||
-ForwardIt は LegacyForwardIterator の要件を満たさなければなりません。 |
[編集]戻り値
(なし) | (C++11未満) |
count > 0 の場合は、最後に代入された要素の次を指すイテレータ。 そうでなければ first 。 | (C++11以上) |
[編集]計算量
count > 0
の場合は、ちょうど count
回の代入。
[編集]例外
テンプレート引数 ExecutionPolicy
を持つオーバーロードは以下のようにエラーを報告します。
- アルゴリズムの一部として呼び出された関数の実行が例外を投げ、
ExecutionPolicy
が標準のポリシーのいずれかの場合は、 std::terminate が呼ばれます。 それ以外のあらゆるExecutionPolicy
については、動作は処理系定義です。 - アルゴリズムがメモリの確保に失敗した場合は、 std::bad_alloc が投げられます。
[編集]実装例
template<class OutputIt, class Size, class T> OutputIt fill_n(OutputIt first, Size count, const T& value){for(Size i =0; i < count; i++){*first++= value;}return first;} |
[編集]例
以下のコードは整数のベクタの左半分に -1 を代入するために fill_n()
を使用します。
Run this code
#include <algorithm>#include <vector>#include <iostream>#include <iterator> int main(){std::vector<int> v1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::fill_n(v1.begin(), 5, -1); std::copy(begin(v1), end(v1), std::ostream_iterator<int>(std::cout, " "));std::cout<<"\n";}
出力:
-1 -1 -1 -1 -1 5 6 7 8 9
[編集]関連項目
指定された要素を範囲内の全要素にコピー代入します (関数テンプレート) |