【问题标题】:Call c++ member function with each element in a list?使用列表中的每个元素调用 c++ 成员函数?
【发布时间】:2010-09-14 00:09:50
【问题描述】:

我有一个Thing 和一个Controller 的列表,我想用notify() 来处理每一件事。下面的代码有效:

#include <algorithm>
#include <iostream>
#include <tr1/functional>
#include <list>
using namespace std;

class Thing { public: int x; };

class Controller
{
public:
    void notify(Thing& t) { cerr << t.x << endl; }
};

class Notifier
{
public:
    Notifier(Controller* c) { _c = c; }
    void operator()(Thing& t) { _c->notify(t); }
private:
    Controller* _c;
};

int main()
{
    list<Thing> things;
    Controller c;

    // ... add some things ...
    Thing t;
    t.x = 1; things.push_back(t);
    t.x = 2; things.push_back(t);
    t.x = 3; things.push_back(t);

    // This doesn't work:
    //for_each(things.begin(), things.end(),
    //         tr1::mem_fn(&Controller::notify));

    for_each(things.begin(), things.end(), Notifier(&c));
    return 0;
}

我的问题是:我可以通过使用“这不起作用”行的某些版本来摆脱 Notifier 类吗?似乎我应该能够做一些事情,但不能完全得到正确的组合。 (我摸索了许多不同的组合。)

不使用提升? (如果可以的话,我会的。)我使用的是 g++ 4.1.2,是的,我知道它很旧...

【问题讨论】:

    标签: c++ stl tr1


    【解决方案1】:

    您可以使用 bind 完成此操作,它最初来自 Boost,但包含在 TR1 和 C++0x 中:

    using std::tr1::placeholders::_1;
    std::for_each(things.begin(), things.end(),
                  std::tr1::bind(&Controller::notify, c, _1));
    

    【讨论】:

    • 谢谢詹姆斯,这正是我想要的。
    【解决方案2】:

    去老学校怎么样:

    for(list<Thing>::iterator i = things.begin(); i != things.end(); i++)
      c.notify(*i);
    

    【讨论】:

    • 因为这太明显了? :) 老实说,这是为了学习,我正在尝试了解新学校的做法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2011-03-23
    相关资源
    最近更新 更多