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()成员函数而不使用迭代器...
你可以这样做std::mem_fun:
std::for_each(list.begin(), list.end(), std::mem_fun(&Interface::run));
Run Code Online (Sandbox Code Playgroud)