`for_each`没有像我预期的那样工作

eri*_*rip 2 c++ algorithm functional-programming bind

我正在使用函数式编程的一些功能,并试图为向量中的每个对象调用成员函数.到目前为止,这是我的代码.

emplace.cc

#include <iostream>
#include <vector>
#include <string>
#include <functional>

class Person {
   public:
      Person(std::string name, size_t age) : _name(name), _age(age) { std::cout << "Hello, " << getName() << std::endl; }
      ~Person() { std::cout << "Goodbye, "<< getName() << std::endl; }
      void greet() { std::cout << getName() << " says hello!" << std::endl; }
      std::string getName() const { return _name; }
   private:
      std::string _name;
      size_t _age;

};

int main()
{
   std::vector<Person> myVector;
   myVector.emplace_back("Hello", 21);
   myVector.emplace_back("World", 20);

   std::for_each(myVector.begin(), myVector.end(), std::bind1st(std::mem_fun(&Person::greet), this));
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

这很可能是有与此代码的问题,但什么是奇怪的是,我的两个错误消息得到.

emplace.cc:24:4: error: 'for_each' is not a member of 'std'
    std::for_each(myVector.begin(), myVector.end(), std::bind1st(std::mem_fun(&Person::greet), this));
    ^
emplace.cc:24:95: error: invalid use of 'this' in non-member function
    std::for_each(myVector.begin(), myVector.end(), std::bind1st(std::mem_fun(&Person::greet), this));
                                                                                               ^
Run Code Online (Sandbox Code Playgroud)

我正在编译-std=c++14使用GCC 5.2.0.

小智 5

for_each 在... <algorithm>

你可以做

for_each(myVector.begin(), myVector.end(), [&] (const decltype(myVector.front())& a) { a.greet(); });
Run Code Online (Sandbox Code Playgroud)