count_if

/*
count_if :返回区间中满足指定条件的元素数目。

template<class InputIterator, class Predicate>

   typename iterator_traits<InputIterator>::difference_type count_if(

      InputIterator _First, 

      InputIterator _Last,

      Predicate _Pred

   );
 
Parameters:

_First 输入迭代器,指向将被搜索的区间第一个元素的位置。

_Last 输入迭代器,指向将被搜索的区间最后一个元素后面的。

_Pred 用户自定义的 predicate function object ,定义了元素被计数需满足的条件。 predicate 只带一个参数,返回 true 或 false.

Return Value:

满足断言(predicate)指定条件的元素数。
*/

#include <vector>
#include <algorithm>
#include <iostream>

bool greater10(int value)
{
    return value >10;
}

int main()
{
    using namespace std;
    vector<int> v1;
    vector<int>::iterator Iter;

    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(10);
    v1.push_back(40);
    v1.push_back(10);

    cout << "v1 = ( ";
    for (Iter = v1.begin(); Iter != v1.end(); Iter++)
       cout << *Iter << " ";
    cout << ")" << endl;

    vector<int>::iterator::difference_type result1;
    result1 = count_if(v1.begin(), v1.end(), greater10);
    cout << "The number of elements in v1 greater than 10 is: "
         << result1 << "." << endl;

	return 0;
}

/*
输出:

v1 = ( 10 20 10 40 10 )
The number of elements in v1 greater than 10 is: 2.
*/


 

 

#include<string>
#include<list>
#include<algorithm>
#include<iostream>
using namespace std;

class cc 
{
public: 
	bool operator()(string &s)
	{
		return s.substr(0,2)=="bb";//前两个字符是bb的
	} 
};

int main()
{
	list<string> a;
	
	a.push_back("bba");
	a.push_back("bbc");
	a.push_back("bbd");
	a.push_back("sef");
	a.push_back("bkp");
	
	cout<<count_if(a.begin(),a.end(),cc());

	return 0;
}

/*
输出:

3
*/


 

 

你可能感兴趣的:(count_if)