C++ 将匿名函数(lambda)另存为函数类型变量

C++ 将匿名函数(lambda)另存为函数类型变量,c++,c++11,lambda,anonymous-function,std-function,C++,C++11,Lambda,Anonymous Function,Std Function,我使用一个匿名函数(也称为lambda)作为find_if的条件。很明显,我可以为它创建一个特殊的类,但是C++11说我可以使用匿名函数。 然而,为了可读性和理解性,我决定将匿名函数保存在一个类型为function的局部变量中 不幸的是,我得到了一个错误: no match for call to '(std::function<bool(Point*, Point*)>) (Point*&)' note: candidate is: note: _Res std::func

我使用一个匿名函数(也称为lambda)作为find_if的条件。很明显,我可以为它创建一个特殊的类,但是C++11说我可以使用匿名函数。 然而,为了可读性和理解性,我决定将匿名函数保存在一个类型为function的局部变量中

不幸的是,我得到了一个错误:

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
对“(std::function)(点*&)”的调用不匹配
注:候选人为:
注意:_resstd::function::operator()(_ArgTypes…)const[带_Res=bool;_ArgTypes={Point*,Point*}]
注:候选者需要2个参数,提供1个
我做错了什么?我对那个所谓的候选人一窍不通。 我试图将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;
}
#包括
#包括
#包括
使用std::vector;
使用std::函数;
使用std::find_if;
点*路径::获取点(整数x,整数y)
{
函数howToFind=[&x,&y](点*a,点*b)->bool
{
如果(a->getX()==x)
{
返回true;
}
否则如果(a->getX()getX())
{
返回true;
}
其他的
{
返回false;
}
};
向量::迭代器foundYa=find_if(this->points.begin(),this->points.end(),howToFind);
如果(foundYa==points.end())
{
返回空ptr;
}
返回*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;
        }
    }
}; 
函数howToFind=[&x,&y](点*a)->bool
{
如果(a==nullptr)
{
返回false;
}
其他的
{
如果(a->getX()==x&&a->getY()==y)
{
返回true;
}
其他的
{
返回false;
}
}
}; 
根据的规定,函数必须是
一元谓词
,即它必须采用单个参数

template< class InputIt, class UnaryPredicate >    
InputIt find_if( InputIt first, InputIt last,
                     UnaryPredicate q );
template
输入查找如果(先输入,后输入,
一元谓词q);

我现在拿到了。因此lambda的语法是正确的,但是lambda的参数在给定的上下文中是不正确的。