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。

異常

如果謂詞或迭代器上的操作丟擲異常,則丟擲異常。

請注意,無效引數會導致未定義的行為。

時間複雜度

firstlast.

的距離的線性時間複雜度。

示例

#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.
algorithm.htm
廣告