目前我正在运行一个 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 算法而不使用成员变量或其他漏洞?
最佳答案
各种 std::bind1st
/std::bind2nd
和 Boost.bind创建库是为了解决您的问题(这对于几乎所有使用 STL 算法的人来说都是常见的),但通常它们看起来只是一种变通方法而不是解决方案。
幸运的是,随着即将到来的 C++ 标准,期待已久的 lambda functions 的加入应该彻底解决问题。但是,请注意,由于 std::for_each
调用仿函数并传递取消引用的迭代器(即正在考虑的实际值),您的 AddToUpdate
函数不应该接受迭代器,但是值(value)。
在这种情况下,它会是这样的:
Update update;
std::foreach(container.begin(); container.end(); [ & update](TypeOfTheValue Value) {
AddToUpdate(Value, update);
});
关于c++ - 是否可以使用具有独立输入参数的函数来使用 STL for_each 算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4455736/