2008-06-25

std::for_each 调用本类的成员函数

std::for_each 是个好用的东西,不过在调用本类的成员函数时稍微遇到点问题。
在网上查找了N久,然后经过自己调试终于得到一个稍微简便的方法:
(结合 std::bind1st 和 std::mem_fun)


// coding by : h_Davy
//
#include <iostream>
#include <vector>

using std::out;

class Test
{
public:
    Test() {};

    void push(int i)
    {
        vi.push_back(i);
    }

    void show()
    {
        std::for_each(
                vi.begin(),
                vi.end(),
                std::bind1st(
                    std::mem_fun<void, Test, int>(
                        &Test::print1 ), this ) );
    }

private:
    std::vector<int> vi;

    void print1(int i)
    {
        cout << "> " << i << "\n";
    }
};


int main()
{
    Test t;

    t.push(123);
    t.push(456);
    t.push(789);

    t.show();

    return 0;
}

(以上代码在 GCC 4 中编译通过,并正常运行)

如果是 MS-VC6 稍微需要些修改:

  1. VC6 中似乎不支持 void 的返回值,所以那个成员函数的返回值改成 int 或 任何你觉得合适的类型。

  2. VC6 中应该将 std::mem_fun 改成 std::mem_fun1 。


如此,VC6 中能正常使用。

//EOF

0 comments: