您的位置:首页 > 其它

Stl中使类成员函数成为谓词,mem_fun 和mem_fun_ref的使用

2010-06-09 20:18 519 查看
STL中仿函数(functors)、类成员和mem_fun的使用

众所周知,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

如果使用mem_fun,会方便很多:

struct D {
D(int i=0){num=i;}
void print() { cout << "I'm a D. my num=" << num<< endl; }
int num;
};

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(), mem_fun(&D::print));
}

这里使用的是vector<D*> V; 在mem_fun_t构造函数中,刚好需要指针,如果不是D*, 而是使用vector<D> V; 还能用吗?

这是你需要使用的是mem_fun_ref。把程序改成:

struct D {
D(int i=0){num=i;}
void print() { cout << "I'm a D. my num=" << num<< endl; }
int num;
};

int main()
{
vector<D> V;

V.push_back(D(1));
V.push_back( D(2));
V.push_back( D());
V.push_back( D(3));

for_each(V.begin(), V.end(), mem_fun_ref(&D::print));
}

那么mem_fun和mem_fun_ref的区别是什么呢?里面的解释是如下:
mem_fun_ref is used to call a member function for objects.
mem_fun adapters are for sequences that contain pointers to elements. Probably mem_fun_ptr would have been a less confusing name for them.
也就是说mem_fun用于容器内是具体对象的情况,而mem_fun用于容器内容是指针的情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: