函数适配器
1.初识函数适配器
1)使用bind2nd进行绑定
2)需要继承 public binary_function<参数类型1,参数类型2,返回值类型>
3)使用const修饰operator()
class myPrint:public binary_function<int,int,void>
{
public:
void operator()(int val,int start) const //限定数据
{
cout<<"val: "<<val<<"start:"<<start<<"val+start= "<<val+start<<endl;
}
};
void text01()
{
vector<int>v;
for (int i=0;i<10;i++)
{
v.push_back(i);
}
cout<<"尊贵的用户请输入起始值:"<<endl;
int num;
cin>>num;
for_each(v.begin(),v.end(),bind2nd(myPrint(),num));
}
2.取反函数适配器
1)使用not1进行取反
2)继承public unary_function<int,bool>
3)使用const修饰operator()
class GreaterThenFive:public unary_function<int,bool>
{
public:
bool operator()(int v)const
{
return v>5;
}
};
void text02()
{
vector<int>v;
for (int i=0;i<10;i++)
{
v.push_back(i);
}
//查找大于5的数字
//vector<int>::iterator pos= find_if(v.begin(),v.end(),not1(GreaterThenFive()));
vector<int>::iterator pos= find_if(v.begin(),v.end(),not1 (bind2nd(greater<int>(),5)));
if (pos!=v.end())
{
cout<<"找到小于5的数字为:"<<*pos<<endl;
}
else
{
cout<<"未找到"<<endl;
}
}
3.函数指针适配器
1)将函数指针适配为函数对象
2)用ptr_fun将函数指针适配为函数对象
void myPrint3(int v,int start)
{
cout<<v+start<<" ";
}
void text03()
{
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(myPrint3),100));
}
4.成员函数适配器
1)如果容器存放的是对象指针, 那么用mem_fun
2)如果容器中存放的是对象实体,那么用mem_fun_ref
class Person
{
public:
Person(string name,int age)
{
this->name=name;
this->age=age;
}
string name;
int age;
void showXinxi()
{
cout<<"姓名:"<<name<<"年龄:"<<age<<endl;
}
};
void text04()
{
vector<Person>v;
Person p1("李亦非",20);
Person p2("冰冰侠",18);
Person p3("李雅婷",22);
Person p4("千峰",23);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
for_each(v.begin(),v.end(),mem_fun_ref(&Person::showXinxi));
}