count_if 功能模板

count_if 功能模板

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

返回满足条件的范围内的元素数

返回值的范围的元素数[first,last)为哪些预解码值是真实的。

此函数模板的行为等效于:

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),它包含所有的元件第一和最后一个,包括由指向的元件第一但不被指向的元素最后。

预计值

一元函数接受范围内的元素作为参数,并返回可转换为的值bool。返回的值表示此函数是否计算元素。
该函数不得修改其参数。
这可以是函数指针或函数对象。

返回值

在范围的元素的数目[first,last)为哪些PRED不返回false
返回类型(iterator_traits :: difference_type)是有符号整数类型。

// 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包含5个奇数值。

复杂

第一个和最后一个之间 的距离线性:为每个元素调用一次pred。

数据竞赛

[first,last)访问 范围中的对象(每个对象只访问一次)。

例外

抛出pre抛出或迭代器上的任何操作抛出时抛出。
请注意,无效参数会导致未定义的行为

See also

count Count appearances of value in range (function template )
for_each Apply function to range (function template )
find Find value in range (function template )

猜你喜欢

转载自www.cnblogs.com/jia0504/p/11374139.html