C++ 中的 Lambda 表达式 std::copy_if.

Lambda Expression in c++ std::copy_if

本文关键字:copy if std 中的 Lambda 表达式 C++      更新时间:2023-10-16

有人可以解释或帮助我为什么这不起作用吗?

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_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),
                    //   ~~~~~~~~~~~~~~~~~^

因为你实际上不知道结果向量会有多少个元素。