for_each中的类方法

时间:2011-10-05 20:32:55

标签: c++ algorithm foreach

有一个类和事件结构:

struct Foo
{
    Foo(): name("nx"), val(9) {}
    string name;
    int val;
};

class Base
{
    public:
        Base()
        {
            /*array.push_back(Foo());
            array.push_back(Foo());
            array.push_back(Foo());             //fill array Foo
            array.push_back(Foo());
            array.push_back(Foo());*/
        }
        void Define(Foo* desktop)
        {
            cout << desktop->name << " " << desktop->val << "\n";
        }

        void Oblem()
        {
            /*for(int i = 0; i < array.size(); ++i)
            {
                Define(&array[i]);
            }*/
            for_each(array.begin(), array.end(), mem_fun_ref(&Base::Define));
        }
    public:
        std::vector<Foo> array;
};

如何在算法for_each?

上替换注释掉的循环

我现在有这些错误:

  1. 错误:无法匹配调用'(std :: mem_fun1_ref_t)(Foo&amp;)'|
  2. 候选人是:_Ret std :: mem_fun1_ref_t&lt; _Ret,_Tp,_Arg&gt; :: operator()(_ Tp&amp;,_ Arg)const [with _Ret = void,_Tp = Base,_Arg = Foo *] |

2 个答案:

答案 0 :(得分:2)

Base::Define有两个参数:Foo* desktop和隐式Base* this。您需要绑定this中的当前Oblem以获取仅需Foo的函数。此外,Define应将其参数设为Foo& desktop(或者更好,如果这是真实代码Foo const& desktop)。

使用TR1中的标准功能(或Boost实现)的完整解决方案将是:

void Define(Foo const& desktop) const
{
    cout << desktop.name << " " << desktop.val << "\n";
}

void Oblem() const
{
    for_each(
        array.begin(), array.end()
      , std::bind( &Base::Define, this, _1 )
    );
}

答案 1 :(得分:2)

class Base
{
public:
    Base() : array(5) {}


    void Define(Foo &desktop)
    {
        cout << desktop.name << " " << desktop.val << "\n";
    }

    void Oblem()
    {
        for_each(array.begin(),array.end(),[this](Foo &f) {
            Define(f);
        });

        // or

        for_each(array.begin(),array.end(),
          bind(&Base::Define,this,placeholders::_1));
    }

public:
    std::vector<Foo> array;
};