- 根据上面的定义,我们可以看出cout_if的工作就是返回给定范围中,符合条件的元素的个数,其中_Pred为比较函数,接受1个参数可以返回一个bool类型的数据。
- template<typename type, int n>
- cout << count(vec_i.begin(),vec_i.end(),4) << endl << endl;
count和count_if用来统计一组数据中满足条件的元素的个数,我们主要 来研究一下count_if,count更简单。
我们先来看一下VS2012中关于count_if的定义
template<class _InIt,
class _Pr> inline
typename iterator_traits<_InIt>::difference_type
_Count_if(_InIt _First, _InIt _Last, _Pr _Pred)
{ // count elements satisfying _Pred
typename iterator_traits<_InIt>::difference_type _Count = 0;
for (; _First != _Last; ++_First)
if (_Pred(*_First))
++_Count;//统计满足谓词_Pred的数据,如果满足,那么_count+1
return (_Count);
}
template<class _InIt, class _Pr> inline
typename iterator_traits<_InIt>::difference_type
count_if(_InIt _First, _InIt _Last, _Pr _Pred)
{ // count elements satisfying _Pred
_DEBUG_RANGE(_First, _Last);
_DEBUG_POINTER(_Pred);
return (_Count_if(_Unchecked(_First), _Unchecked(_Last), _Pred)); //可以看出这只是张皮,只是处理一下异常,真正干活的函数在上面
}
bool tiaojian(const type& num)
{
return num < n;
}
比如上面的函数就可以作为count_if的第三个参数,我们可以这么写count_if(vec.begin(),vec.end(),tiaojian<int,10> ) ;其中vec是一个vector<int>类型的数据。这样就可以统计出vec中小于10的元素的个数。
同样,count的用法和count_if的用法相似,只不过,第三个参数不是一个谓词,而是一个具体的数据,向下面的语句:
执行之后就会输出 容器vec_i中等于4的元素的个数
参考资料:VS2012 algorithm头文件
以上均为个人观点,如果有错误,请大家指正,如果有什么地方没有说明白也可以在下面留言。
