【问题标题】:Is it possible to use the STL for_each algorithm using a function with independent input parameters?是否可以使用具有独立输入参数的函数来使用 STL for_each 算法?
【发布时间】:2010-12-15 22:47:10
【问题描述】:

目前我正在运行一个 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 算法而不使用成员变量或其他漏洞?

【问题讨论】:

    标签: c++ stl stl-algorithm


    【解决方案1】:

    创建了各种std::bind1st/std::bind2ndBoost.bind 库来解决您的问题(这对几乎所有使用STL 算法的人来说都很常见),但它们通常只是一种解决方法而不是解决方案。

    幸运的是,随着即将推出的 C++ 标准,期待已久的 lambda functions 的添加应该可以彻底解决问题。但是,请注意,由于 std::for_each 调用函子传递了取消引用的迭代器(即正在考虑的实际值),因此您的 AddToUpdate 函数不应该接受迭代器,而是接受值。

    在这种情况下,它会是这样的:

    Update update;
    std::foreach(container.begin(); container.end(); [ & update](TypeOfTheValue Value) {
        AddToUpdate(Value, update);
    });
    

    【讨论】:

    • 另一种选择是编写一个仿函数来完成这项工作。这将实现类似于 lambda 版本的行为,但不需要 C++0x 的编译器支持。
    【解决方案2】:

    你想使用std::bind2nd() - http://www.cplusplus.com/reference/std/functional/bind2nd/

    基本上它从带有 2 个参数的函数返回一个一元函数对象,其中第二个参数是固定的。

    这就是你的代码在for_eachbind2nd 下的样子:

    Update update;
    for_each(container.begin(), container.end(), bind2nd(ptr_fun(AddToUpdate), update));
    

    编辑。 正如 Matteo 注意到的那样,AddToUpdate 的第一个参数必须是容器中的值类型,而不是迭代器。

    【讨论】:

    • 但这仅适用于派生自 std::binary_function 的函子,不适用于函数。
    • 正确,已编辑。我习惯了boost::bind,所以忘记了纯STL是多么痛苦。
    • 这种方法的一个问题是它不能与引用一起使用,因为 bind2nd 尝试也将第二个参数用作引用,从而导致对引用的非法引用。看起来我在最初的问题中错过了这一点信息。
    • 你总是可以使用boost::bind。我发现使用 STL 更舒服。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多