| 类别: 算法 | 组件类型: 函数 |
template <class InputIterator, class UnaryFunction> UnaryFunction for_each(InputIterator first, InputIterator last, UnaryFunction f);
template<class T> struct print : public unary_function<T, void>
{
print(ostream& out) : os(out), count(0) {}
void operator() (T x) { os << x << ' '; ++count; }
ostream& os;
int count;
};
int main()
{
int A[] = {1, 4, 2, 8, 5, 7};
const int N = sizeof(A) / sizeof(int);
print<int> P = for_each(A, A + N, print<int>(cout));
cout << endl << P.count << " objects printed." << endl;
}
[1] 此返回值有时很有用,因为函数对象可能具有局部状态。例如,它可能计算被调用的次数,或者可能具有一个状态标志以指示调用是否成功。