目前我正在运行一个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算法而不使用成员变量或其他漏洞?
答案 0 :(得分:4)
您想使用std::bind2nd()
- http://www.cplusplus.com/reference/std/functional/bind2nd/
基本上它从带有2个参数的函数返回一元函数对象,其中第二个参数是固定的。
这就是您的代码在for_each
和bind2nd
:
Update update;
for_each(container.begin(), container.end(), bind2nd(ptr_fun(AddToUpdate), update));
编辑。由于Matteo注意到AddToUpdate
的第一个参数必须是容器中的值类型,而不是迭代器。
答案 1 :(得分:4)
创建了各种std::bind1st
/ std::bind2nd
和Boost.bind库来解决您的问题(几乎所有使用STL算法的人都会这样做),但通常他们只是看起来像解决方法而不是解决方案。
幸运的是,随着即将到来的C ++标准,期待已久的lambda functions的添加应该最终解决问题。但请注意,由于std::for_each
调用函数传递解除引用的迭代器(即正在考虑的实际值),因此AddToUpdate
函数不应接受迭代器,而应接受值。
在这种情况下,它会是这样的:
Update update;
std::foreach(container.begin(); container.end(); [ & update](TypeOfTheValue Value) {
AddToUpdate(Value, update);
});