.find_if(v.begin() , v.end() , mygreate ): //第三个参数为对象(匿名对象也可以)
适配器
(1)函数适配器:bind2nd绑定,继承binary_function(参1,参2 ,返回值),函数加const常函数;
(2)取反适配器:not1绑定,继承unary_function(参数1,返回值),函数加const;
(3)普通函数指针适配器:ptr_fun将函数指针适配为函数对象,在2nd参数绑定;
(4)成员函数适配器:mem_fun_ref(), 作用域
代码—常用适配器的使用
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
#include<functional>
//-------------------------------------------------------------------------------------------
//函数适配器
class myPrint:public binary_function<int ,int ,void>//一参数,二参数,返回值类型;
{
public:
void operator()(int val ,int num) const//const不能忘
{
cout<<val+num<<endl;
}
};
void test01()
{
vector<int> v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
int num;
cin>>num;
for_each(v.begin(),v.end(),bind2nd(myPrint(),num));//多绑定一个参数,继承与const;
}
//-------------------------------------------------------------------------------------------
//一元取反适配器
class Greater:public unary_function<int ,bool>
{
public:
bool operator()(int val) const
{
return val>5;
}
};
void test02()
{
vector<int> v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
vector<int>::iterator it = find_if(v.begin(),v.end(),not1(Greater()));//not1,继承,const
cout<<"小于5的数字为:"<<*it<<endl;
}
//-------------------------------------------------------------------------------------------
//普通函数指针适配器
void myprint(int val,int start)
{
cout<<val+start<<endl;
}
void test03()
{
vector<int> v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
for_each(v.begin(),v.end(),bind2nd(ptr_fun(myprint),10));//ptr_fun先将函数适配为函数对象,在绑定
}
//-------------------------------------------------------------------------------------------
//成员函数适配器
class Person
{
public:
Person(string name ,int age)
{
m_Name=name;
m_Age = age;
}
void showPerson()
{
cout<<"姓名:"<<m_Name<<"年龄;"<<m_Age<<endl;
}
string m_Name;
int m_Age;
};
void test04()
{
vector<Person> v;
Person p1("aaa",10);
Person p2("bbb",20);
Person p3("ccc",30);
Person p4("ddd",40);
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::showPerson));//mem_fun_ref,作用域
}
//-------------------------------------------------------------------------------------------
int main()
{
test04();
//test03();
//test02();
//test01();
return 0;
}