algorithm头文件定义了一个count的函数,其功能类似于find。这个函数使用一对迭代器和一个值做参数,返回这个值出现次数的统计结果。

编写程序读取一系列int型数据,并将它们存储到vector对象中,然后统计某个指定的值出现了多少次。

count(数组开头,数组结尾,数组要找的对象);

核心代码:cout<

样例:

#include

#include

#include

#include

using namespace std;

int main()

{

int a[1000],n;

scanf("%d",&n);

for(int i = 0;i < n; i++)

{

scanf("%d",a + i);

}

int m;

scanf("%d",&m);

printf("%d\n",count(a,a+n,m));

return 0;

}

有了这个函数,就不用循环一个一个搜索了!!!

这里还有一个更强的函数:count_if

count_if(数组开头,数组结尾,要满足的条件【1】)

【1】:满足条件可以用自定义函数,定义函数,返回判断值。

样例:

#include #include#include

bool greater10(intvalue)

{return value >10;

}intmain()

{using namespacestd;

vectorv1;

vector::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<

vector::size_type result1 = count_if(v1.begin(), v1.end(), greater10); //count_if算法返回使谓词函数返回条件成立的元素个数

cout << "The number of elements in v1 greater than 10 is:"

<< result1 << "." <

}

最后,阿姆镇楼!!!

更多推荐

mysql 统计多个countif_algorithm库———count&&countif