函数适配器
-
-
- 函数适配器: 扩展函数的参数接口(假如函数有一个参数 再扩展一个接口 据可以传递两个参数)
- 函数适配器
-
- 案例
- 案例:bind2nd 或bind1st区别
-
- bind2nd:讲外界数据 绑定到第二个参数
- bind1st:讲外界数据 绑定到第一个参数
- 取反适配器(not1一元取反)
-
-
- not1一元取反
- not2二元取反
- 注意:
-
- binary_function 二元继承
- unary_function 一元继承
- 案例2:二元取反not2
- 成员函数适配器(mem_fun_ref)
- 普通函数作为适配器(ptr_fun)

函数适配器: 扩展函数的参数接口(假如函数有一个参数 再扩展一个接口 据可以传递两个参数)
函数适配器
案例
class MyPrint:public binary_function<int,int, void>
{
public:
void operator()(int val,int tmp) const
{
cout<<val+tmp<<" ";
}
};
void test05()
{
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(50);
for_each(v.begin(), v.end(), bind2nd(MyPrint(),1000) );
cout<<endl;
}
运行结果:

案例:bind2nd 或bind1st区别
bind2nd:讲外界数据 绑定到第二个参数
bind1st:讲外界数据 绑定到第一个参数
void test05()
{
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(50);
cout<<"bind2nd"<<endl;
for_each(v.begin(), v.end(), bind2nd(MyPrint(),1000) );
cout<<endl;
cout<<"--------------------"<<endl;
cout<<"bind1st"<<endl;
for_each(v.begin(), v.end(), bind1st(MyPrint(),1000) );
cout<<endl;
}
运行结果:


取反适配器(not1一元取反)
not1一元取反
not2二元取反
class MyGreaterThan3:public unary_function<int,bool>
{
public:
bool operator()(int val)const
{
return val>3;
}
};
void test06()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
vector<int>::iterator ret;
ret = find_if(v.begin(),v.end(), MyGreaterThan3() );
if(ret != v.end())
{
cout<<"*ret = "<<*ret<<endl;
}
ret = find_if(v.begin(),v.end(), not1(MyGreaterThan3()) );
if(ret != v.end())
{
cout<<"*ret = "<<*ret<<endl;
}
}
运行结果:

注意:
binary_function 二元继承
unary_function 一元继承
案例2:二元取反not2
class MyGreaterInt:public binary_function<int,int,bool>
{
public:
bool operator ()(int v1,int v2)const
{
return v1>v2;
}
};
void test07()
{
vector<int> v;
v.push_back(2);
v.push_back(1);
v.push_back(5);
v.push_back(3);
v.push_back(4);
for_each(v.begin(),v.end(), [](int v){cout<<v<<" ";});
cout<<endl;
sort(v.begin(),v.end(), not2(greater<int>()));
for_each(v.begin(),v.end(), [](int v){cout<<v<<" ";});
cout<<endl;
}
运行结果:

成员函数适配器(mem_fun_ref)
class Person
{
public:
string name;
int age;
Person(string name,int age)
{
this->name = name;
this->age = age;
}
void showPerson()
{
cout<<"name = "<<this->name<<",age="<<this->age<<endl;
}
};
void myPrintPerson(Person &ob)
{
cout<<"name = "<<ob.name<<",age="<<ob.age<<endl;
}
void test08()
{
vector<Person> v;
v.push_back(Person("德玛西亚",18));
v.push_back(Person("狗头",28));
v.push_back(Person("牛头",19));
v.push_back(Person("小法",38));
for_each(v.begin(),v.end(), mem_fun_ref(&Person::showPerson) );
}
运行结果:

普通函数作为适配器(ptr_fun)
void myPrintInt01(int val,int tmp)
{
cout<<val+tmp<<" ";
}
void test01()
{
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
for_each(v.begin(),v.end(), bind2nd(ptr_fun(myPrintInt01),1000));
cout<<endl;
}
运行结果;
