count 函数(C++)用法
·
count函数可以用来统计字符串中某个字符的个数,或数组中某个元素的数量。
使用方法是count(begin,end,‘a’),其中begin指的是起始地址,end指的是结束地址,第三个参数指的是需要查找的字符。
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string s = "aaabcdaaa!!!";
int cnt= count(s.begin(),s.end(),'b');
cout <<"在字符串" << s << "中" <<"字母b出现的次数是" << cnt << endl;
return 0;
}
数组中元素的数量:
#include<iostream>
#include<algorithm>
using namespace std;
int a[7] = { 1, 2, 3, 3, 4, 4, 45};
vector<int> nums(a, a+7);
int main(){
int cnt = count(nums.begin(),nums.end(), 3);
cout << cnt << endl;//输出2
return 0;
}
更多推荐
已为社区贡献4条内容
所有评论(0)