对于vector,我们可以很方便地寻找其中符合条件的元素的个数。
要注意它们不是vector的类函数,不要用vector.去调用。
用法一览:
一.count函数: 返回元素值为target的元素个数。
int num=count(vector1.begin(),vector2.begin(),target); //注意不是vector的类函数哟!!
二.count_if函数:返回符合一定条件的元素个数。compare()函数是自定义的,返回值是true就是表示符合要求。
(例题via孙宇洪)
其实comp比较函数才是整个count_if函数的核心,comp比较函数是编程的人写的,返回值是一个布尔型,我相信看完我的例题后,就可以理解这个函数的应用。例题:统计1-10奇数的个数(我的代码):
#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
发现了函数的奥秘了吗?我们来看一下count_if函数STL的源代码:
template <class InputIterator, class Predicate>
ptrdiff_t count_if ( InputIterator first, InputIterator last, Predicate pred )
{
ptrdiff_t ret=0;
while (first != last)
if (pred(*first++)) ++ret;
return ret;
}
再看一个例题:输入一串学生的信息,统计出成绩大于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函数的复杂度是线性的,在数据量大的时候,要使用更加好的方法。
定睛一看,这位博主是初中的时候写的。。。。。。我@#@$#%$^%^^&&^*(。。。。。。