Cpp-standard-library-cpp-algorithm-copy-if

提供:Dev Guides
移動先:案内検索

C ++アルゴリズムライブラリ-copy_if()関数

説明

C ++関数* std
algorithm :: copy_if()*は、predicateが値に対してtrueを返す場合、要素の範囲を新しい場所にコピーします。

宣言

以下は、std
algorithmヘッダーからのstd :: algorithm :: copy_if()関数の宣言です。

C 11

template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if(InputIterator first,InputIterator last,
   OutputIterator result,UnaryPredicate pred);

パラメーター

  • first -検索されたシーケンスの初期位置に反復子を入力します。
  • last -検索されたシーケンスの最終位置に反復子を入力します。
  • result -新しいシーケンスの初期位置にイテレータを出力します。
  • pred -引数を取り、ブール値を返す単項述語。

戻り値

結果シーケンスに書き込まれた最後の要素に続く要素を指す反復子を返します。

例外

要素の割り当てまたはイテレータの操作が例外をスローした場合、例外をスローします。

無効なパラメータは未定義の動作を引き起こすことに注意してください。

時間の複雑さ

`+ first `から ` last +`までの距離は線形です。

次の例は、std
algorithm :: copy_if()関数の使用法を示しています。
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool predicate(int n) {
   return (n %2 != 0);
}

int main(void) {
   vector<int> v1 = {1, 2, 3, 4, 5};
   vector<int> v2(3);

   copy_if(v1.begin(), v1.end(), v2.begin(), predicate);

   cout << "Following are the Odd numbers from vector" << endl;

   for (auto it = v2.begin(); it != v2.end(); ++it)
      cout << *it << endl;

   return 0;
}

上記のプログラムをコンパイルして実行すると、次の結果が生成されます-

Following are the Odd numbers from vector
1
3
5