I have a question regarding the following piece of code.
template <typename T>
struct DisplayElementKeepCount
{
int m_nCount;
DisplayElementKeepCount () { m_nCount = 0; }
void operator () (const T& element){++ m_nCount; cout<<element<<‘ ‘;}
};
when calling, it is written as:
DisplayElementKeepCount <int> mResult;
mResult = for_each ( vecIntegers.begin (), vecIntegers.end (), DisplayElementKeepCount <int> () );
I don't quite understand, because operator() needs a parameter "element", but it was not included when being called. why?
The example of IsMultiple actually gives a parameter when called. Why are these two different??
template <typename numberType>
struct IsMultiple
{
numberType m_Divisor;
IsMultiple (const numberType& divisor)
{
m_Divisor = divisor;
}
// The comparator of type: bool f(x)
bool operator () (const numberType& element) const
{
// Check if the dividend is a multiple of the divisor
return ((element % m_Divisor) == 0);
}
};
...
vector <int>::iterator iElement;
iElement = find_if ( vecIntegers.begin (), vecIntegers.end (),
IsMultiple <int> (4) );
IsMultiple
, notoperator()
. The parameter tooperator()
is passed to the functor inside the algorithm for each element in the range.