替代std :: bind2nd [英] A replacement for std::bind2nd

查看:246
本文介绍了替代std :: bind2nd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个foo,它是一个std::vector<int>.它代表一组范围的边缘"值.

I have a foo which is a std::vector<int>. It represents the "edge" values for a set of ranges.

例如,如果foo为{1、3、5、7、11},则范围为1-3、3-5、5-7、7-11.对我而言,重要的是,这相当于4个周期.请注意,每个句点都包含一个范围内的第一个数字,而不是最后一个数字.因此,在我的示例中,第8个(从零开始)周期中出现8. 7也出现在第3期中. 11及以上不会出现在任何地方. 2在第0期出现.

For example, if foo is {1, 3, 5, 7, 11} then the ranges are 1-3, 3-5, 5-7, 7-11. Significantly for me, this equates to 4 periods. Note that each period includes the first number in a range, and not the last one. So in my example, 8 appears in the 3rd (zero-based) period. 7 also appears in the 3rd period. 11 and above doesn't appear anywhere. 2 appears in the 0th period.

给出一个bar,它是一个int,我用

Given a bar which is an int, I use

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

给我应该包含bar的时期.

to give me the period that should contain bar.

我的问题:std::bind2nd已过时,因此我应该重构.使用更新功能的等效语句是什么? std::bind不会以明显的方式插入".

My problem: std::bind2nd is deprecated so I ought to refactor. What is the equivalent statement using updated functions? std::bind doesn't "drop in" in the obvious way.

推荐答案

在C ++ 11中,您可以使用std::bind;只是不太明显如何使用它:

In C++11, you can use std::bind; it just isn't as obvious how to use it:

#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调用内使用的占位符显示了调用结果对象时提供的参数如何映射到要绑定到的可调用对象的参数列表.因此,例如:

The key is the use of the placeholder argument, which are declared in the std::placeholders namespace. std::bind returns a function object that takes some number of parameters when it is invoked. The placeholders used inside the call to std::bind show how the arguments provided when the resulting object is invoked map to the argument list to the callable that you're binding to. So, for instance:

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)

这篇关于替代std :: bind2nd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆