当前位置:编程学习 > C/C++ >>

count与count_if详解

声明:以后所有函数的讨论和前面一样,都是在vs2010基础上.
count有两个功能相似的函数:一个是本身另一个是count_if
首先是count:
函数功能:返回区间取值为_Val的元素个数.
template<class _InIt,
         class_Ty> inline
         typenameiterator_traits<_InIt>::difference_type
                   _Count(_InIt _First, _InIt_Last, const _Ty& _Val)
         {       // count elements that match _Val
         typenameiterator_traits<_InIt>::difference_type _Count = 0;
 
         for (;_First != _Last; ++_First)
                   if(*_First == _Val)
                            ++_Count;
         return(_Count);
         }
 
template<class _InIt,
         class_Ty> inline
         typenameiterator_traits<_InIt>::difference_type
                   count(_InIt _First, _InIt_Last, const _Ty& _Val)
         {       // count elements that match _Val
         _DEBUG_RANGE(_First, _Last);
         return(_Count(_Unchecked(_First), _Unchecked(_Last), _Val));
         }
这个函数为只读函数(并不改变迭代器区间的值).
count_if:
函数功能:返回对区间的每个值对_Pred都是true的个数
template<class _InIt,
         class_Pr> inline
         typenameiterator_traits<_InIt>::difference_type
                   _Count_if(_InIt _First, _InIt_Last, _Pr _Pred)
         {       // count elements satisfying _Pred
         typenameiterator_traits<_InIt>::difference_type _Count = 0;
 
         for (;_First != _Last; ++_First)
                   if(_Pred(*_First))
                            ++_Count;
         return(_Count);
         }
 
template<class _InIt,
         class_Pr> inline
         typenameiterator_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));
         }
注意:由函数得知:_Pred只有一个参数.函数返回difference_type.
template<typenameT>
class CountFunc
{
public:
         bool operator()( T _Value )
         {
                   return!( _Value % 2 == 0 );
         }
};
int main()
{
         vector<int>vecInt;
         vecInt.push_back( 2 );
         vecInt.push_back( 5 );
         vecInt.push_back( 7 );
         vecInt.push_back( 3 );
         vecInt.push_back( 2 );
         vecInt.push_back( 4 );
         vecInt.push_back( 3 );
         vecInt.push_back( 7 );
         vecInt.push_back( 3 );
         int i =count( vecInt.begin(),vecInt.end(),2);
         cout<<i<<"\n";
         int_iCount = count_if( vecInt.begin(),vecInt.end(),CountFunc<int>());
         cout<<"countresult:"<<_iCount;
         system( "pause");
         return0;
}



摘自 yuanweihuayan的专栏
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,