count主要用来统计容器内元素个数,其格式有两种:
第一种,第三个参数为元素值
template<class _InIt,
class _Ty> inline
typename iterator_traits<_InIt>::difference_type
count(_InIt _First, _InIt _Last, const _Ty& _Val)
第二种,第三个参数为条件函数:
template<class _InIt,
class _Pr> inline
typename iterator_traits<_InIt>::difference_type
count_if(_InIt _First, _InIt _Last, _Pr _Pred)
程序实例:
#include<iostream>
#include<functional>
#include<algorithm>
#include<vector>
template<typename T>
int PushNum(T &vec, int first, int last) {
int ret = 0;
if (first > last) {
ret = -1;
cout << "function PushNum first > last error:" << ret << endl;
}
while (first <= last) {
vec.push_back(first);
first++;
}
return ret;
}
template<typename T>
void print(T &ele) {
cout << ele << " ";
}
bool isEven(int &ele) {
return ele % 2 == 0;
}
using namespace std;
int main(){
vector<int> vec;
PushNum(vec, 1, 10);
for_each(vec.begin(), vec.end(), print<int>);
cout << endl;
int count1 = count(vec.begin(), vec.end(), 5);
int count2 = count_if(vec.begin(), vec.end(), isEven);
int count3 = count_if(vec.begin(), vec.end(), bind2nd(greater<int>(), 2));
cout << count1 << endl;
cout << count2 << endl;
cout << count3 << endl;
system("pause");
return 0;
}
输出结果:
第一个count是求元素值等于5的个数,第二个count是求满足偶数的个数,第三个count是求大于2的个数。