函式模板
<algorithm>

std::count_if

template <class InputIterator, class UnaryPredicate>  typename iterator_traits<InputIterator>::difference_type    count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
返回範圍內滿足條件的元素數量
返回範圍 [first,last)pred 為 true 的元素數量。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
11
template <class InputIterator, class UnaryPredicate>
  typename iterator_traits<InputIterator>::difference_type
    count_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  typename iterator_traits<InputIterator>::difference_type ret = 0;
  while (first!=last) {
    if (pred(*first)) ++ret;
    ++first;
  }
  return ret;
}

引數

first, last
輸入迭代器 指向序列的起始和結束位置。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
pred
一元函式,它接受範圍中的一個元素作為引數,並返回一個可轉換為 bool 的值。返回值表示該元素是否被此函式計數。
該函式不得修改其引數。
這可以是一個函式指標,也可以是一個函式物件。

返回值

範圍 [first,last)pred 不返回 false 的元素數量。
返回型別(iterator_traits<InputIterator>::difference_type)是帶符號整數型別。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// count_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::count_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> myvector;
  for (int i=1; i<10; i++) myvector.push_back(i); // myvector: 1 2 3 4 5 6 7 8 9

  int mycount = count_if (myvector.begin(), myvector.end(), IsOdd);
  std::cout << "myvector contains " << mycount  << " odd values.\n";

  return 0;
}

輸出
myvector contains 5 odd values.


複雜度

線性複雜度,與 firstlast 之間的 距離 成正比:對每個元素呼叫一次 pred

資料競爭

範圍 [first,last) 中的物件將被訪問(每個物件恰好訪問一次)。

異常

如果 pred 丟擲異常,或者對迭代器的任何操作丟擲異常,則丟擲異常。
請注意,無效引數會導致未定義行為

另見