c++ - std::bind2nd 的替代品

标签 c++ c++11 bind bind2nd

我有一个 foo这是 std::vector<int> .它表示一组范围的“边缘”值。

例如,如果 foo是 {1, 3, 5, 7, 11} 那么范围是 1-3, 3-5, 5-7, 7-11。对我来说很重要,这相当于 4 个时期。请注意,每个句点包括范围中的第一个数字,而不是最后一个数字。因此,在我的示例中,8 出现在第 3 个(从零开始)期间。 7也出现在第三期。 11 及以上不会出现在任何地方。 2出现在第0期。

给定一个 bar这是一个int , 我用

std::find_if(
    foo.begin(),
    foo.end(),
    std::bind2nd(std::greater<int>(), bar)
) - foo().begin() - 1;

给我应该包含 bar 的句点.

我的问题:std::bind2nd已弃用,所以我应该重构。使用更新函数的等效语句是什么? std::bind不会以明显的方式“插入”。

最佳答案

在C++11中,你可以使用std::bind;只是如何使用它并不那么明显:

#include <functional>
using namespace std::placeholders;
std::find_if(
    foo.begin(),
    foo.end(),
    // create a unary function object that invokes greater<int>::operator()
    // with the single parameter passed as the first argument and `bar` 
    // passed as the second argument
    std::bind(std::greater<int>(), _1, bar)
) - foo().begin() - 1;

关键是占位符参数的使用,它在 std::placeholders 命名空间中声明。 std::bind 返回一个函数对象,该对象在被调用时带有一定数量的参数。在对 std::bind 的调用中使用的占位符显示了在调用结果对象时提供的参数如何映射到您要绑定(bind)到的可调用对象的参数列表。所以,例如:

auto op1 = std::bind(std::greater<int>(), _1, bar);
op1(5); // equivalent to std::greater<int>()(5, bar)

auto op2 = std::bind(std::greater<int>(), bar, _1);
op2(5); // equivalent to std::greater<int>()(bar, 5)

auto op3 = std::bind(std::greater<int>(), _2, _1);
op3(5, bar); // equivalent to std::greater<int>()(bar, 5)

auto op4 = std::bind(std::greater<int>(), _1, _2);
op4(5, bar); // equivalent to std::greater<int>()(5, bar)

关于c++ - std::bind2nd 的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50440564/

相关文章:

c++ - 嵌套初始化列表的构造函数

c++ - 如何确定 std::type_index 是否对我的编译器是唯一的?

c - 绑定(bind)失败 : : Address family not supported by protocol family - C

javascript 和 c++ 双数 0.0

c++ - linux下的firefox插件开发

c++ - 弃用 static 关键字...不再?

javascript - JavaScript 构造函数类中元素的firstChild

c++ - 计算偶数平均值时出现浮点异常错误

c++ - 我如何使用QTable?添加、编辑、删除和检索行

c++ - 返回 std::function 的类 std::bind 函数