有人可以解释或帮助我为什么这不起作用吗?
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)); ^
最佳答案
std::mem_fun
是一个已弃用的辅助函数,可能是 soon removed from the standard library. std::mem_fn
会是更好的选择。
此外,如果你想将 std::mem_fn
、std::mem_fun
或 std::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),
// ~~~~~~~~~~~~~~~~~^
因为您实际上并不知道生成的 vector 有多少个元素。
关于c++ - C++ std::copy_if 中的 Lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27634681/