程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> count與count_if詳解

count與count_if詳解

編輯:C++入門知識

聲明:以後所有函數的討論和前面一樣,都是在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的專欄

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved