我有一个foo,它是一个std::vector<int>。它表示一组范围的“边缘”值。
例如,如果foo是{1,3,5,7,11},那么范围是1-3,3-5,5-7,7-11。对我来说,这相当于4个周期。请注意,每个句点包括范围内的第一个数字,而不是最后一个数字。所以在我的例子中,8出现在第三个(基于零的)时期。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不会以明显的方式“插入”。
发布于 2015-09-23 12:04:07
在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时使用的占位符显示了调用结果对象时提供的参数如何将参数列表映射到绑定到的可调用对象。因此,例如:
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)发布于 2015-09-23 12:06:29
从石器时代(bind2nd)直奔铁器时代( C++14 generic ),绕过青铜时代(bind),怎么样?
std::find_if(foo.begin(), foo.end(), [&](auto const& elem) {
return elem > bar;
}); 如果输入被排序
std::lower_bound(foo.begin(), foo.end(), bar); Lambdas读取起来比std::bind表达式容易得多,也更易于内联。参见Lavevej's CppCon 2015 talk。
发布于 2015-09-23 12:04:43
bind版本将是:
bind(std::greater<int>(), placeholders::_1, bar)但我认为,使用lambdas更受鼓励,例如:
[bar](const int a){return bar < a;}还鼓励使用重载函数begin/end而不是方法调用。所以就像:
find_if(begin(foo), end(foo), [bar](const int a){return bar < a;})https://stackoverflow.com/questions/32739018
复制相似问题