1、函数适配器
如果函数对象仅有一个输入但是需要多个输入,可采用函数适配器bind1st和bind2nd绑定要输入的参数即可,同时需要我们自己的函数对象继承binary_function(二元函数对象)或者 unary_function(一元函数对象)。
class my_Print :public binary_function<int,int,void>//<第一个参数类型,第二个参数类型,返回值>
{
public:
void operator()(int val1,int val2) const{
cout << "val1= : " << val1<< " val2= :" <<val2<< " val1+val2 = :" << (val1+ val2) << endl;}
};
void test()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
cout << "请输入起始值:" << endl;
int origin;
cin >> origin;
//bind1st bind2nd将二元函数对象转为一元函数对象
for_each(v.begin(), v.end(), bind2nd(my_Print(), origin));//bind2nd将参数绑定为函数对象的第二个参数
//for_each(v.begin(), v.end(), bind1st(my_Print(),origin));//bind1st将参数绑定为函数对象的第一个参数
}
同时因为函数对象可以有自己的状态所以也可以在函数对象内定义成员变量,通过有参构造来进行,这就是使用函数对象的好处。
class my_Print{
public:
my_Print(int add):m_Add(add){};
void operator()(int value){
cout<<value+m_Add<<" ";
}
private:
int m_Add;
};
int main(){
int add;
cin>>add;
for_each(v.begin(),v.end(),my_Print(add));
//for_each(v.begin(), v.end(), bind2nd(my_Print(),add));
return 0;
}
2、函数指针适配器
函数指针适配器ptr_fun( )可以把一个普通的函数指针适配成函数对象,从而使用。
void my_Print(int val1,int val2)
{
cout << val1 + val2<< " ";
}
void test()
{
vector <int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
// ptr_fun( )把一个普通的函数指针适配成函数对象
for_each(v.begin(), v.end(), bind2nd(ptr_fun(my_Print), 100));
}