gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:56 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com