STL中bind2nd的用法

比如我们有下面的类:

class ClxECS
{
public:
    int DoSomething() 
    { 
        // 这里以输出一句话来代替具体的操作
        cout << "Output from method DoSomething!" << endl; 
        return 0; 
    };
};
    和下面的一个vector:

vector<ClxECS*> vECS;

for (int i = 0; i < 13; i++)
{
    ClxECS *pECS = new ClxECS;
    vECS.push_back(pECS);
}
    如果要对容器vECS中的所有对象都进行DoSomething()的操作,可以用下面的方法:

for_each(vECS.begin(), vECS.end(), mem_fun(&ClxECS::DoSomething));
    (关于mem_fun的用法可以参考我的那篇《STL中mem_fun和mem_fun_ref的用法》)
    当然,我们也可以用下面的方法:

int DoSomething(ClxECS *pECS)
{
    return pECS->DoSomething();
}

for_each(vECS.begin(), vECS.end(), &DoSomething);
    从上面的代码可以看到,两种方法其实都是调用类ClxECS的DoSomething()方法。在这里,方法DoSomething()是没有参数的,如果这个方法像下面那样是有参数的,该用什么方法传递参数呢?

class ClxECS
{
public:
    int DoSomething(int iValue)
    {
        cout << "Do something in class ClxECS!" << endl;
        cout << "The input value is: " << iValue << endl;
        return 0;
    }
};
    这个时候就该我们的bind2nd登场了!下面是具体的代码:

// mem_fun1是mem_fun支持一个参数的版本
for_each(vECS.begin(), vECS.end(), bind2nd(mem_fun1(&ClxECS::DoSomething), 13));
    或者:

int DoSomething(ClxECS *pECS, int iValue)
{
    return pECS->DoSomething(iValue);
}

for_each(vECS.begin(), vECS.end(), bind2nd(ptr_fun(DoSomething), 13));
    从上面的代码可以看出,bind2nd的作用就是绑定函数子的参数的。可是STL只提供了对一个参数的支持。如果函数的参数多于1个,那就无能为力了。
posted on 2010-05-31 23:35  carekee  阅读(396)  评论(0编辑  收藏  举报