2014-12-24 25 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()' –