C++ 中的 Lambda 表达式 std::copy_if.
Lambda Expression in c++ 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:
};
目前我收到此错误,
调用"mem_fun(布尔值)"没有匹配函数 auto checkIF = std::mem_fun(p->IFHigherThan(value)); ^
std::mem_fun
是一个废弃的辅助函数,可能很快就会从标准库中删除。 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),
// ~~~~~~~~~~~~~~~~~^
因为你实际上不知道结果向量会有多少个元素。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- std::filesystem::copy throws filesystem_error
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 使用if-else将数字转换为单词
- 为什么简单的算术减法在"if"条件下不起作用?
- 以在Qt中的IF语句中设置时间延迟