首页 / 软件开发 / C++ / STL中仿函数(functors)、类成员和mem_fun的使用
STL中仿函数(functors)、类成员和mem_fun的使用2010-07-15winter众所周知,STL使用起来非常方便,其中仿函数(functor)扮演了一个非常重要的角色。灵活运用仿函数的使用对于发挥STL强大功能非常关键。本文详细介绍了如何使用mem_fun和mem_fun1来绑定类成员函数,使之成为functor什么是仿函数?就是一个重载了"()"运算符的struct,例如:struct print_obj{ void operator(int a)const{ cout<<a<<endl; } };在STL的许多算法(algorithm)中都需要使用functor. 如:for_each. 同样在关联容器中也需要使用functor, 如map, set等。经常在使用STL算法的时候,经常需要把仿函数和类联系在一起,如果可以直接使用类的成员函数作为仿函数,那就方便多了。mem_fun的功能就是如此。先看个简单的例子:struct D { D(int i=0){num=i;} int num; }; struct print_D{ void operator()(const D* d)const{ cout<<"I am D. my num="<<d->num<<endl; } };
int main() { vector<D*> V; V.push_back(new D(1)); V.push_back(new D(2)); V.push_back(new D); V.push_back(new D(3)); for_each(V.begin(), V.end(), print_D()); }编译输出:I am D. my num=1 I am D. my num=2 I am D. my num=0 I am D. my num=3