根据effective STL的rule,从效率和正确性角度考虑,使用STL的算法要比自己写循环遍历要effective。之前一直没讲究过这个。从现在起,要注意起来了。先学起来下面三个

1. find

2. find_if

3. for_each

它们都会用到mem_fun, mem_fun1(可以接受一个参数),bind2nd(ptr_fun(funcName), argument)。详见下面的例子(来自:http://www.builder.com.cn/2008/0129/723326.shtml)

比如我们有下面的类: 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)); // 对每个element调用其成员函数DoSomething()


    (关于mem_fun的用法可以参考我的那篇《STL中mem_fun和mem_fun_ref的用法》)

    当然,我们也可以用下面的方法:

int DoSomething(ClxECS *pECS)

{

return pECS->DoSomething();

}


for_each(vECS.begin(), vECS.end(), &DoSomething); // 对每个element调用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个,那就无能为力了。