有人可以解释或帮助我为什么这不起作用?
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)); ^
答案 0 :(得分:2)
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),
// ~~~~~~~~~~~~~~~~~^
因为你实际上并不知道结果向量有多少元素。