count()函数
algorithm头文件定义了一个count的函数,其功能类似于find。这个函数使用一对迭代器和一个值做参数,返回这个值出现次数的统计结果
#include algorithm
cout<<count(ivec.begin() , ivec.end() , searchValue)
#include <iostream>
#include <algotirhm>
#include <string>
using namespace std;
int main()
{
string temp = "aaabcdaaa!!!";
int num = count(temp.begin(),temp.end(),'a');
cout <<"在字符串" << temp << "中," <<"字母a出现的次数是" << num << endl;
return 0 ;
}
count_if()函数
返回区间中满足指定条件的元素数目
#include <vector>
#include <algorithm>
#include <iostream>
bool greater10(int value)
{
return value >10;
}
int main()
{
using namespace std;
vector<int> v1;
vector<int>::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 << endl;
vector<int>::size_type result1 = count_if(v1.begin(), v1.end(), greater10); //count_if算法返回使谓词函数返回条件成立的元素个数
cout << "The number of elements in v1 greater than 10 is: "
<< result1 << "." << endl;
return 0;
}
📌 count_if()函数需要结合谓词函数使用