2014-10-27 93 views
0

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

不幸的是,我得到的错误:

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; 
     } 
    } 
}; 

回答

2

根据cppreference功能必须是UnaryPredicate,即它必须采取的一个参数。

template< class InputIt, class UnaryPredicate >  
InputIt find_if(InputIt first, InputIt last, 
        UnaryPredicate q); 
+0

我明白了。 所以lambda的语法是正确的,但lambda的参数在给定的上下文中是不正确的。 – RoestVrijStaal 2014-11-10 18:33:12