使用std :: bind从BinaryPredicate中创建UnaryPredicate以在std :: transform中使用

时间:2013-09-10 20:29:32

标签: c++ c++11 stdbind

我最近遇到了for_each的使用:

std::for_each(ts.begin(), ts.end(), [=](T& t){t *= f;});

嗯,它有效。对于Ts和T f的容器,这将每个值乘以f。但是我不喜欢这里使用lambda。它很简短,但在我看来它只复制std::multiplies。此外,它不应该for_each,而应transform来表达修改的意图。

但是,std::multiplies是二元谓词,std::transform需要一元谓词。

我试图将f绑定为一个参数,但显然我错误地使用了它:

std::transform(ts.begin(), ts.end(), std::bind(std::multiplies<T>(), f));

海湾合作委员会试图给我一个提示错误信息,但我没有看到实际原因:

no matching function for call to ‘transform(std::vector<int>::iterator, std::vector<int>::iterator, std::_Bind_helper<false, std::multiplies<int>, const int&>::type)’

我怀疑我使用std::bind错了。我的错是什么?

1 个答案:

答案 0 :(得分:3)

您忘记了结果范围的迭代器和bind-expression中的占位符:

std::transform(
    ts.begin(), ts.end(), // source range
    ts.begin(),           // beginning of result range
    std::bind(std::multiplies<int>(), f, std::placeholders::_1) );
    //                                   ^^^^^^^^^^^^^^^^^^^^^
    //                                   this is where the value from
    //                                   dereferenced source iterator go