1.介绍
A. 函数原型:
作用:查找[first, last)区间内值为val的元素的个数
2.分析
A. 头文件:algorithm
B.可以作用于一般的数组,也可以作用于STL容器
3.使用
A.一般数组
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int a[5] = {1, 2, 3, 2, 1};
cout << count(a, a + 5, 0) << endl; // 0
cout << count(a, a + 5, 2) << endl; // 2
string b[5] = {"a", "c", "c", "hello", "c"};
cout << count(b, b + 5, "hello") << endl; // 1
cout << count(b, b + 5, "c") << endl;// 3
}
B.容器
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
vector<int> v = {-1, 0, 1, 2, 2};
cout << count(v.begin(), v.end(), 2) << endl; // 2
if(count(v.begin(), v.end(), 0) == 1){
cout << "数字1的个数为1" << endl;
}
}