algorithm头文件定义了一个count的函数,其功能类似于find。这个函数使用一对迭代器和一个值做参数,返回这个值出现次数的统计结果。
编写程序读取一系列int型数据,并将它们存储到vector对象中,然后统计某个指定的值出现了多少次(代码中向量的那种方式)。
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
//count函数的用法
vector<int> v(10);
int a[10] = { 1, 2, 3, 4, 4, 4, 4 };
v[0] = 1;
v[1] = 1;
v[2] = 1;
v[3] = 1;
v[4] = 1;
v[5] = 1;
v[6] = 6;
v[7] = 7;
v[8] = 8;
v[9] = 9;
//向量计数
cout << count(v.begin(), v.end(), 1) << endl;
cout << count(v.begin(), v.end(), 5) << endl;
cout << count(v.begin(), v.end(), 6) << endl;
cout << endl;
//数组计数
cout << count(a, a + 10, 0) << endl;
cout << count(a, a + 10, 1) << endl;
cout << count(a, a + 10, 4) << endl;
system("pause");
return 0;
}