用于普通操作的STD一元函数
std unary functions for common operations
是否有理由不为函数中的二进制函数提供一元版本?
我知道通过使用std::bind
创建一元版本很简单,但是代码看起来很难看:
std::find_if(std::begin(v), std::end(v), std::bind(std::less_equal<int>(), std::placeholders::_1, 42));
我想如果有这样的东西会更好:
std::find_if(std::begin(v), std::end(v), std::less_equal<int>(42));
IMHO自c++ 11/14以来,lambda使这种谓词变得多余?
find_if(begin(v), end(v), [](auto x){ return x <= 42; });
我认为没有技术上的理由不允许你的第二种方法。在弃用之前,std::bind2nd
辅助函数将非常接近您想要的方法:
std::find_if(std::begin(v), std::end(v), std::bind2nd(std::less_equal<int>(), 42));
当然你也可以创建自己的helper——它很短:
template <typename T> auto cmp_less_equal(const T& x) {
return std::bind(std::less_equal<T>(), std::placeholders::_1, x);
}
现在你可以写
std::find_if(std::begin(v), std::end(v), cmp_less_equal(42));
使用你自己的包装器
给lambda一个名字怎么样?
const auto cmp_less_eq = [](auto x){ return x <= 42; };
const auto result = find_if(begin(v), end(v), cmp_less_eq);
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- 如何在 std::transform 中使用 std::p ow 作为一元函数?
- 位集构造函数中的一元按位或折叠
- 替换包含已弃用的一元函数的自定义模板
- 为什么指向非静态成员函数的指针不能用作标准库算法的一元谓词
- 具有成员函数的一元谓词
- 在函数调用之前,一元运算符会否定运算符
- C++逻辑为真的一元函数
- 如何从函数模板类成员内的转换算法参数指向一元运算符函数
- 运算符重载:一元运算符重载函数返回在此代码中如何工作
- 将一元函数应用于向量的某些元素的良好实现是什么?
- 使用 +(一元加号)解决 lambda 的函数指针和 std::function 上的不明确重载
- 一元函数,接受迭代器元组并产生基本类型
- 用于普通操作的STD一元函数