通过下面例题我们可以更清楚的理解
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
bool comp(int num)
{
return num%2;
}
int main()
{
vector <int> V;
for(int i=1;i<=10;i++)
V.push_back(i);
cout<<count_if(V.begin(),V.end(),comp)<<endl;
return 0;
}
输出:5
再看一个例题:输入一串学生的信息,统计出成绩大于90分的同学个数(我的代码):
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
struct student
{
string name;
int score;
};
bool compare(student a)
{
return 90<a.score;
}
int main()
{
int n;
cin>>n;
vector<student> V;
for(int i=0;i<n;i++)
{
student temp;
cin>>temp.name>>temp.score;
V.push_back(temp);
}
cout<<count_if(V.begin(),V.end(),compare)<<endl;
return 0;
}
看了代码之后,理解这个函数就不难了。注意:count函数和count_if函数的复杂度是线性的,在数据量大的时候,要使用更加好的方法。