c++ - C++ std::copy_if 中的 Lambda 表达式

标签 c++ lambda shared-ptr

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

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

因为您实际上并不知道生成的 vector 有多少个元素。

关于c++ - C++ std::copy_if 中的 Lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27634681/

相关文章:

c++ - 为什么我在 C++ 中用 ^ 计算指数时得不到正确的结果?

c++ - 如果涉及 `this`,则无法在构造函数中初始化 Shared_ptr

c++ - 尝试理解 std::enable_shared_from_this<T> 但使用它会导致 bad_weak_ptr

c++ - 转换 View 的 std::prev 上的未定义行为

c++ - 我应该在哪里保存我的着色器代码?

c++ - 具有自定义值类型的 map::emplace()

c++ - 通用 vector 类中的重载解析问题

python-2.7 - 如何用lambda表达式初始化字典中的键、值对?

java - 使用 Java8 lambda 在模拟类上进行参数匹配

c++ - 在模块(exes和dlls)之间使用STL(TR1)shared_ptr是否安全