1. difference_type count (InputIterator beg, InputIterator end, const T& value);
2. difference_type count_if (InputIterator beg, InputIterator end, UnaryPredicate op);
1式返回beg-end区间内等于value的值,2式返回beg-end区间内使op为真的数量。
注意:
- 返回值difference_type类型是用来描述两个迭代器之间距离的类型。
- op操作不能改变区间内的值。
- op的状态在运行期间不能更改
注:可能好奇的你就要问为什么不能改变区间的值了,我就变了咋地吧,为了打消你这个疑虑,我们去看一下count_if的源码。
template<class _InIt,
class _Pr> inline
_Iter_diff_t<_InIt> count_if(_InIt _First, _InIt _Last, _Pr _Pred)
{ // count elements satisfying _Pred
_DEBUG_RANGE(_First, _Last);
auto _UFirst = _Unchecked(_First);
const auto _ULast = _Unchecked(_Last);
_Iter_diff_t<_InIt> _Count = 0;
for (; _UFirst != _ULast; ++_UFirst)
{
if (_Pred(*_UFirst))
{
++_Count;
}
}
return (_Count);
}
通过阅读源码,我们清晰的看出,我们对区间内的每一个元素动执行了_Pred操作,但是并没有指出如果我们改变了原有的值,程序会出现何种异常。嗯,所以,少年如果你真的想通过该函数改变区间中的值并没有任何语法上的错误,但是仍然不提倡变更区间内的值。
void main()
{
std::vector<int>v1{1,2,3,4,5,6,7,8};
cout<<count_if(v1.begin(), v1.end(), [](int & n)//非常不提倡该种做法
{
return(++n > 3);
})<<endl;
for (const auto &i:v1)
{
cout << i <<ends;
}
}
输出结果:6
2 3 4 5 6 7 8 9
你看,上面例子完全没有任何错误,输出的结果也是我们预期结果,但是真的真的不建议这么使用!!!
void main()
{
std::vector<int>v1{1,2,9,2,3,5,3,4,5,6,7,4,2,8};
int num = std::count(v1.begin(),v1.end(),5);
cout<< "number of elements equal to 5: "<< num << endl;
num = std::count_if(v1.begin(),v1.end(),[](int n)
{
return ( n % 2 == 0 );
});
cout<<num;
}
输出:number of elements equal to 5:2
7