好了,有了以上理论知识,就可以探讨一下函数对象的用法了,接下来我会以STL中使用最频繁的for_each做例子,来说明函数对象的原理和作用。
先查一下for_each的用法,在www.cplusplus.com上查到了比较详细的解释,原文如下:
Apply function to range
Applies function f to each of the elements in the range [first,last) .The behavior of this template function is equivalent to:
template<class InputIterator, class Function> Function for_each(InputIterator first, InputIterator last, Function f) { for ( ; first!=last; ++first ) f(*first); return f; }