std::partition_copy
| ヘッダ <algorithm> で定義
|
||
| (1) | ||
| template< class InputIt, class OutputIt1, class OutputIt2, class UnaryPredicate > |
(C++11以上) (C++20未満) |
|
| template< class InputIt, class OutputIt1, class OutputIt2, class UnaryPredicate > |
(C++20以上) | |
| template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3, class UnaryPredicate > |
(2) | (C++17以上) |
[first, last) の要素を、述語 p の返す値によって、2つの異なる範囲にコピーします。 述語 p を満たす要素は d_first_true から始まる範囲にコピーされます。 残りの要素は d_first_false から始まる範囲にコピーされます。policy に従って実行されます。 このオーバーロードは、 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> が true である場合にのみ、オーバーロード解決に参加します。目次 |
[編集] 引数
| first, last | - | コピーする要素の範囲 |
| d_first_true | - | p を満たす要素の出力範囲の先頭 |
| d_first_false | - | p を満たさない要素の出力範囲の先頭 |
| policy | - | 使用する実行ポリシー。 詳細は実行ポリシーを参照してください |
| p | - | 要素が d_first_true に置かれるべき場合に true を返す単項述語。 式 p(v) は |
| 型の要件 | ||
-InputIt は LegacyInputIterator の要件を満たさなければなりません。
| ||
-InputIt を逆参照した型は CopyAssignable の要件を満たさなければなりません。
| ||
-OutputIt1, OutputIt2 は LegacyOutputIterator の要件を満たさなければなりません。
| ||
-ForwardIt1, ForwardIt2, ForwardIt3 は LegacyForwardIterator の要件を満たさなければなりません。 ForwardIt1 の値型は CopyAssignable を満たさなければならず、 ForwardIt2 および ForwardIt3 に書き込み可能でなければならず、 UnaryPredicate の引数型に変換可能でなければなりません。
| ||
-UnaryPredicate は Predicate の要件を満たさなければなりません。
| ||
[編集] 戻り値
d_first_true の範囲の終端を指すイテレータと d_first_false の範囲の終端を指すイテレータから構築された std::pair。
[編集] 計算量
ちょうど distance(first, last) 回の p の適用。
ExecutionPolicy を取るオーバーロードの場合、 ForwardIt の値型が CopyConstructible でなければ性能上のコストが生じることがあります。
[編集] 例外
テンプレート引数 ExecutionPolicy を持つオーバーロードは以下のようにエラーを報告します。
- アルゴリズムの一部として呼び出された関数の実行が例外を投げ、
ExecutionPolicyが標準のポリシーのいずれかの場合は、 std::terminate が呼ばれます。 それ以外のあらゆるExecutionPolicyについては、動作は処理系定義です。 - アルゴリズムがメモリの確保に失敗した場合は、 std::bad_alloc が投げられます。
[編集] 実装例
template<class InputIt, class OutputIt1, class OutputIt2, class UnaryPredicate> std::pair<OutputIt1, OutputIt2> partition_copy(InputIt first, InputIt last, OutputIt1 d_first_true, OutputIt2 d_first_false, UnaryPredicate p) { while (first != last) { if (p(*first)) { *d_first_true = *first; ++d_first_true; } else { *d_first_false = *first; ++d_first_false; } ++first; } return std::pair<OutputIt1, OutputIt2>(d_first_true, d_first_false); } |
[編集] 例
#include <iostream> #include <algorithm> #include <utility> int main() { int arr [10] = {1,2,3,4,5,6,7,8,9,10}; int true_arr [5] = {0}; int false_arr [5] = {0}; std::partition_copy(std::begin(arr), std::end(arr), std::begin(true_arr),std::begin(false_arr), [] (int i) {return i > 5;}); std::cout << "true_arr: "; for (int x : true_arr) { std::cout << x << ' '; } std::cout << '\n'; std::cout << "false_arr: "; for (int x : false_arr) { std::cout << x << ' '; } std::cout << '\n'; return 0; }
出力:
true_arr: 6 7 8 9 10 false_arr: 1 2 3 4 5
[編集] 関連項目
| 指定範囲の要素を2つのグループに分割します (関数テンプレート) | |
| 相対的な順序を維持しながら要素を2つのグループに分割します (関数テンプレート) | |
| (C++11) |
指定範囲の要素を新しい位置にコピーします (関数テンプレート) |
| 指定範囲の要素から一定の基準を満たすものを除いてコピーします (関数テンプレート) |