将匿名函数(lambda)保存为函数类型变量
Saving an anonymous function (lambda) as function-typed variable
我使用一个匿名函数(也称为lambda)作为find_if的条件。很明显,我可以为它创建一个特殊的类,但C++11说我可以为此使用一个匿名函数。然而,为了可读性和理解性,我决定将匿名函数保存在类型为函数的局部变量中。
不幸的是,我得到了错误:
no match for call to '(std::function<bool(Point*, Point*)>) (Point*&)'
note: candidate is:
note: _Res std::function<_Res(_ArgTypes ...)>::operator()(_ArgTypes ...) const [with _Res = bool; _ArgTypes = {Point*, Point*}]
note: candidate expects 2 arguments, 1 provided
我做错了什么?所谓的候选人对我来说是希腊语。我试图将lambda直接放在find_if-invokement中,但也不起作用。
#include <vector>
#include <function>
#include <algorithm>
using std::vector;
using std::function;
using std::find_if;
Point* Path::getPoint( int x, int y )
{
function<bool( Point*, Point* )> howToFind = [&x, &y]( Point* a, Point* b ) -> bool
{
if( a->getX() == x )
{
return true;
}
else if( a->getX() < b->getX() )
{
return true;
}
else
{
return false;
}
};
vector<Point*>::iterator foundYa = find_if( this->points.begin(), this->points.end(), howToFind );
if( foundYa == points.end() )
{
return nullptr;
}
return *foundYa;
}
cnicutar给出有用答案后,代码的更正部分。我不得不在其他地方重构我的代码,但这超出了这个问题的范围:
function<bool( Point* )> howToFind = [&x, &y]( Point * a ) -> bool
{
if( a == nullptr )
{
return false;
}
else
{
if( a->getX() == x && a->getY() == y )
{
return true;
}
else
{
return false;
}
}
};
根据cppreference,函数必须是UnaryPredicate
,即它必须采用单个参数。
template< class InputIt, class UnaryPredicate >
InputIt find_if( InputIt first, InputIt last,
UnaryPredicate q );
相关文章:
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 是否可以保存带有参数的函数指针以供以后使用?
- 在每个运行时将函数保存到相同的地址
- 如何使用 pybind11 将 python 函数保存到静态 c++ 容器中?
- 为什么添加析构函数(甚至是空的)会破坏我的结构,该结构使用 ref 转发和折叠来保存 ref 或值的副本?
- (UE4)在标头中保存lambda函数
- 使用函数指针时,ESP 未在函数调用中正确保存
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- 无法绑定可变参数函数并保存到 std::函数
- 获取线函数未定义错误。无法在字符串中保存可验证的内容
- 如何在程序后台运行函数(特别是自动保存函数)?QT / C++
- C++ 函数将多余的空条目保存到文件中
- clang格式:如何将构造函数的初始值设定项列表的每个元素保存在单独的行上
- 使用setW()函数保存文件时,如何获取每个属性的值
- 从 strtok 函数保存值
- 将函数保存在数组C++中
- 如何将函数指针中的函数保存为类的成员函数?
- 将它们(函数)保存在内存中的同一位置
- 将lambda表达式或函数保存为二进制文件