當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Algorithm count_if()用法及代碼示例


描述

C++ 函數std::algorithm::count_if()返回範圍內滿足條件的值出現的次數。

聲明

以下是 std::algorithm::count_if() 函數形式 std::algorithm 頭文件的聲明。

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。

返回值

返回範圍內的元素數返回真。

異常

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

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

時間複雜度

之間的距離呈線性第一的最後的

示例

下麵的例子展示了 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.

相關用法


注:本文由純淨天空篩選整理自 C++ Algorithm Library - count_if() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。