2014-12-24 24 views
0

有人可以解释或帮助我为什么这不起作用吗?C++中的Lambda表达式std :: copy_if

std::vector<std::shared_ptr<Publication> > Bibliography::givePubWithIFHigherThan(float value) const 
    { 
    Publication *p; 
    std::vector<std::shared_ptr<Publication>> highIFPubs(publications); 
    auto checkIF = std::mem_fun(p->IFHigherThan(value)); 
    auto last = std::copy_if(publications.begin(), publications.end, highIFPubs.begin(), 
          [=] (std::shared_ptr<Publication> p) 
          { 
          return checkIF(*p, value); 
          }); 
    return highIFPubs; 

    } 



class Publication 
    { 
    public: 
    Publication(std::string aTitle, int aYear, std::string anID); 
    virtual bool IFHigherThan(float value) const {return false;}; 

    private: 

    }; 


class Paper : public Publication 
    { 
    public: 
    Paper(std::string aTitle, int aYear, std::string aJournal, float aImpactFactor); 
    bool IFHigherThan(float value) const {return value < impactFactor;}; 


    private: 


    }; 

目前,我得到这个错误,

 
no matching function for call to 'mem_fun(bool)' 
    auto checkIF = std::mem_fun(p->IFHigherThan(value)); 
                ^
+2

这是因为你正在调用IFHigherThan函数,而不是传递指针。 –

+0

但是p是一个指针吧? – user4390280

+0

是的,'p'是一个指针,但是'p-> IFHigherThan(value)'是一个函数调用,导致一个'bool'。 –

回答

2

std::mem_fun是depracated辅助函数,可能会soon removed from the standard library.std::mem_fn将是一个更好的选择。

而且,如果你想使用std::mem_fnstd::mem_funstd::bind与函数,那么你在指针传递给函数,而不是一个调用表达式,所以不是:

auto checkIF = std::mem_fun(p->IFHigherThan(value)); 

使用:

auto checkIF = std::mem_fn(&Publication::IFHigherThan); 

另外,不使用任何包装,只需直接调用所选择的成员函数:

auto last = std::copy_if(publications.begin(), publications.end(), highIFPubs.begin(), 
         [=] (std::shared_ptr<Publication> p) 
         { 
         return p->IFHigherThan(value); 
         }); 

有你在你的代码多了一个逻辑错误:

std::vector<std::shared_ptr<Publication>> highIFPubs(publications.size()); 

应该是:

std::vector<std::shared_ptr<Publication>> highIFPubs; 

,然后代替:

auto last = std::copy_if(publications.begin(), publications.end() 
         , highIFPubs.begin(), 
        // ~~~~~~~~~~~~~~~~~^ 

,你应该使用std::back_inserter

auto last = std::copy_if(publications.begin(), publications.end() 
         , std::back_inserter(highIFPubs), 
        // ~~~~~~~~~~~~~~~~~^ 

因为您实际上不知道合成矢量有多少元素。

+0

谢谢,我的copy_if函数仍然有错误。这种方式使用lambda有问题吗? – user4390280

+0

仍然有相同的错误。 没有匹配函数调用'copy_if(std :: vector > :: const_iterator,<未解析的重载函数类型>,std :: vector > ::迭代器,参考书目: :givePubWithIFHigherThan(float)const :: __ lambda0)' }); ^ – user4390280

+0

@ user4390280因为你有一个错字:'.end'而不是'.end()' –