本文介绍了为什么std :: for_each(from,to,function)返回函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是读了std :: for_each的代码:

I just read the code for std::for_each:

template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f)
{
  for ( ; first!=last; ++first ) f(*first);
  return f;
}

,并且看不到此模板函数返回输入函数的任何好的理由。

and could not see any good reasons for this template function to return the input function. Does anyone have any examples on where this would be useful?

推荐答案

这是为了让你在你的函数中累积状态,然后返回它到你的调用代码。例如,你的函数(作为函子类)可以有一个成员int用于计算它被调用的次数。

It's to allow you to accrue state in your function and then return it to your calling code. For instance, your function (as a functor class) could have a member int for counting the number of times it had been called.

这里是一个包含一些例子的页面:

Here is a page with some examples : http://xenon.arcticus.com/c-morsels-std-for-each-functors-member-variables

这篇关于为什么std :: for_each(from,to,function)返回函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:41