函数原型:
template <class InputIterator, class UnaryPredicate> typename iterator_traits<InputIterator>::difference_type count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
功能:
在范围内返回满足条件元素的个数。
返回范围[first, last)范围内是pred为true的元素个数。
函数的行为与以下函数相等:
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)包括了first到last的所有元素,包括first迭代器
指向的元素,但是不包括last迭代器指向的元素。
pred:
一元函数接受范围内的一个元素作为参数,并返回一个可以转换为bool的值。这返回值意味着这元素是否被函数计算
在内。该函数不应该修改它的参数。这个参数可以是一个函数指针或者函数对象。
返回值:
在范围[first,last)中使pred返回true的元素个数。这返回值的类型为有符号的int型。
例子:
// 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.
时间复杂度:
O(n)
原文:https://www.cnblogs.com/haideshiyan35/p/14497728.html