如何使用std :: for_each?

kle*_*vre 1 c++ algorithm foreach

是否可以使用std :: for_each或其他类似的东西?

#include <list>
#include <algorithm>

// Class declaration
//
struct Interface
{
   virtual void run() = 0;
};

struct A : public Interface
{
   void run() { std::cout << "I run class A" << std::endl; }
};

struct B : public Interface
{
   void run() { std::cout << "I run class B" << std::endl; }
};

// Main
//
int main()
{
   // Create A and B
   A a;
   B b;

   // Insert it inside a list
   std::list<Interface *> list;
   list.push_back(&a);
   list.push_back(&b);

   // Then execute a func with for_each without recreate a func which call Interface::run() 
   std::for_each(list.begin(), list.end(), run);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑:我的问题是:如何使用算法或更简单的C++方式调用循环内的每个run()成员函数而不使用迭代器...

Gre*_*ill 8

你可以这样做std::mem_fun:

std::for_each(list.begin(), list.end(), std::mem_fun(&Interface::run));
Run Code Online (Sandbox Code Playgroud)

  • `std :: mem_fn`是C++ 11的正确函数,不推荐使用`std :: mem_fun`,因为它只适用于1(或2?)个参数函数. (5认同)
  • @Seth:`std :: bind(&Inerface :: run,_1)`,有什么问题? (5认同)
  • 请记住它在C++ 11中被弃用为`std :: mem_fn`. (2认同)