Declaration: in the future, all functions will be discussed on the basis of vs2010.
Count has two similar functions: one is itself and the other is count_if
The first is count:
Function: returns the number of elements with a range value of _ 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 ));
}
This function is a read-only function (without changing the iterator range value ).
Count_if:
Function: returns the number of true pairs for each value in the interval.
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 ));
}
Note: The function knows that _ Pred has only one parameter. The function returns 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;
}
From yuanweihuayan's column