Cpp-standard-library-cpp-algorithm-count-if

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

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

説明

C ++関数* std
algorithm :: count_if()*は、条件を満たす範囲の値の出現回数を返します。

宣言

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

C 98

template <class InputIterator, class Predicate>
typename iterator_traits<InputIterator>::difference_type
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);

パラメーター

  • first -検索されたシーケンスの初期位置に反復子を入力します。
  • last -検索されたシーケンスの最終位置に反復子を入力します。
  • pred -引数を取り、boolを返す単項述語。

戻り値

`+ pred +`がtrueを返す範囲内の要素の数を返します。

例外

述語またはイテレータの操作が例外をスローした場合、例外をスローします。

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

時間の複雑さ

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

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

using namespace std;

bool predicate(int n) {
   return (n > 3);
}

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

   cnt = count_if(v.begin(), v.end(), predicate);

   cout << "There are " << cnt << " numbers are greater that 3." << endl;

   return 0;
}

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

There are 2 numbers are greater that 3.