是否可以使用具有独立输入参数的函数来使用STL for_each算法?
目前,我正在运行一个 for 循环,在其中对 STL 容器中的每个元素进行调用,类似于以下内容。
void AddToUpdate(iterator iter, Update& Update) {...};
...
Update update;
for(iterator iter = container.begin(); iter != container.end(); ++iter)
AddToUpdate(iter, update);
我正在研究 for_each STL 算法,因为它似乎适合我的需要。
我想知道,考虑到应用到容器的函数使用了第二个输入参数,是否可以重构它以使用标准 STL 算法而不使用成员变量或其他漏洞?
At the moment I am running a for loop where I make a call on each element in an STL container, similar to the following.
void AddToUpdate(iterator iter, Update& Update) {...};
...
Update update;
for(iterator iter = container.begin(); iter != container.end(); ++iter)
AddToUpdate(iter, update);
I am looking at the for_each STL algorithm as it seems to fit my needs.
I was wondering if, given the use of a second input parameter to the function being applied to the container, whether it's possible to refactor this to use a standard STL algorithm without using member variables or other loopholes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
各种
std::bind1st
/std::bind2nd
和 Boost.bind 库是为了解决您的问题而创建的(这对于几乎所有使用 STL 算法的人来说都是常见的),但是通常它们看起来只是一种解决方法而不是解决方案。幸运的是,随着即将推出的 C++ 标准,期待已久的 lambda 函数 的添加应该可以实现彻底解决问题。但是,请注意,由于
std::for_each
调用传递取消引用的迭代器(即正在考虑的实际值)的函子,因此您的AddToUpdate
函数不应接受迭代器,但值。在这种情况下,它会是这样的:
The various
std::bind1st
/std::bind2nd
and the Boost.bind library were created to solve your problem (that is common to almost anyone who used the STL algorithms), but often they just seem a workaround instead of a solution.Fortunately, with the upcoming C++ standard the long-awaited addition of lambda functions should solve definitively the problem. However, notice that, since
std::for_each
calls the functor passing the dereferenced iterator (i.e. the actual value being considered) yourAddToUpdate
function shouldn't accept the iterator, but the value.In such case, it would be something like this:
您想要使用
std::bind2nd()
- http: //www.cplusplus.com/reference/std/function/bind2nd/基本上它从具有 2 个参数的函数返回一个一元函数对象,其中第二个参数是固定的。
使用
for_each
和bind2nd
时,您的代码应如下所示:编辑。 正如 Matteo 注意到
AddToUpdate
的第一个参数一样> 必须是容器中值的类型,而不是迭代器。You want to use
std::bind2nd()
- http://www.cplusplus.com/reference/std/functional/bind2nd/Basically it return a unary function object from function with 2 arguments, where the second argument is fixed.
This is how your code should look like with
for_each
andbind2nd
:Edit. As Matteo noticed the first argument of
AddToUpdate
has to be type of value in container, not an iterator.