【STL】count_if

功能

返回满足条件的元素个数

模版

template <class InputIterator, class Predicate>
  typename iterator_traits<InputIterator>::difference_type  //返回值
    count_if (InputIterator first, InputIterator last, UnaryPredicate pred); 

实现

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;
}

参数

  1. first, last: 输入迭代器指出首尾的位置,范围是[first, last),即包括第一个而不包括last。
  2. pred: 一元函数名字,接收范围内的一个元素作为参数,返回bool值。函数不得修改其参数。可以为函数指针或函数对象。

案例

案例1. pred为bool函数

代码

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool IsOdd(int i)
{
    return ((i % 2) == 1);
}
int main()
{
    vector<int> vec;
    for(int i=0; i<10; ++i)
        vec.push_back(i);
    int mycount = count_if(vec.begin(), vec.end(), IsOdd);
    cout << "My vector contains " << mycount << " odd values." << endl;
}

输出

案例2. pred为函数对象

代码

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class GT_cls
{
    public:
        GT_cls(int val) : bound(val) {}
        bool operator()(const string &s)
        { return s.size() >= bound; }
    private:
        string::size_type bound;
};
int main()
{
    vector<string> vec;
    vec.push_back("hello1");
    vec.push_back("hello12");
    vec.push_back("hello123");
    vec.push_back("hello1234");
    vec.push_back("hello12345");
    GT_cls tmp(7);  //函数对象比函数更灵活
    cout << count_if(vec.begin(), vec.end(), tmp) << endl;
}

输出

4

复杂度

O(1)

参考

http://www.cplusplus.com/reference/algorithm/count_if/

原文地址:https://www.cnblogs.com/kaituorensheng/p/3505927.html