#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
using namespace std;
struct myprint : public binary_function<int,int,void>
{
void operator()(int v,int val) const
{
cout<<"v:"<<v<<"val:"<<val<<" ";
cout<<v+val<<endl;
}
};
//仿函数适配器 bindlst bind2nd 绑定适配器
void text01()
{
vector<int> v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
int num=200;
for_each(v.begin(),v.end(),bind2nd(myprint(),num));
//绑定适配器 将一个二元的函数对象转为一元函数对象
//bind2nd:
/*
v:0val:200 200
v:1val:200 201
v:2val:200 202
v:3val:200 203
v:4val:200 204
v:5val:200 205
v:6val:200 206
v:7val:200 207
v:8val:200 208
v:9val:200 209
*/
for_each(v.begin(),v.end(),bind1st(myprint(),num));
/*v:200val:0 200
v:200val:1 201
v:200val:2 202
v:200val:3 203
v:200val:4 204
v:200val:5 205
v:200val:6 206
v:200val:7 207
v:200val:8 208
v:200val:9 209*/
//两者区别:1st,将num绑定为函数对象第一个参数;2nd将Num绑定为函数对象的第二个参数
}
struct myprint02
{
void operator()(int v)
{
cout<<v<<" ";
}
};
struct compare:public binary_function<int,int,bool>
{
bool operator()(int a,int b)const
{
return a>b;
}
};
struct mygreater5: public unary_function<int,bool>//一元是unary_function
{
bool operator()(int v)const
{
return v>5;
}
};
//仿函数适配器 not1 not2 取反适配器
void text02()
{
srand(time(NULL));
vector<int> v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
sort(v.begin(),v.end(),compare());
for_each(v.begin(),v.end(),myprint02());
cout<<endl;
sort(v.begin(),v.end(),not2(compare()));
for_each(v.begin(),v.end(),myprint02());
/*
81 61 34 31 26 21 16 15 11 9
9 11 15 16 21 26 31 34 61 81
*/
//not1 not2 区别:not1 用于一元谓词,not2用于二元谓词
vector<int>::iterator it=find_if(v.begin(),v.end(),not1(mygreater5()));//找第一个大于5的元素的迭代器
if(it==v.end())
{
cout<<"no find"<<endl;
}
else
cout<<*it<<endl;//0
}
//仿函数适配器 ptr_fun
void myprint03(int val,int val2)
{
cout<<"val:"<<val<<"val2:"<<val2<<endl;
cout<<val+val2<<endl;
}
void text03()
{
vector<int> v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
//把普通函数适配成函数对象
for_each(v.begin(),v.end(),bind2nd(ptr_fun(myprint03),10));
/*
val:0val2:10
10
val:1val2:10
11
val:2val2:10
12
val:3val2:10
13
val:4val2:10
14
val:5val2:10
15
val:6val2:10
16
val:7val2:10
17
val:8val2:10
18
val:9val2:10
19
*/
}
class person
{
public:
person(int age,int id):age(age),id(id)
{
}
public:
void show()
{
cout<<"age:"<<age<<" id:"<<id<<endl;
}
public:
int age;
int id;
};
//成员函数适配器 mem_fun mem_fun_ref
void text04()
{
//如果容器中存放的对象或者对象指针,我们for_each算法打印的时候,调用类自己提供的打印函数
vector<person> v;存实值
person p1(10,20),p2(30,40),p3(50,60);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
//格式: &类名::函数名
for_each(v.begin(),v.end(),mem_fun_ref(&person::show));
vector<person*> v1;//存指针
v1.push_back(&p1);
v1.push_back(&p2);
v1.push_back(&p3);
for_each(v1.begin(),v1.end(),mem_fun(&person::show));
/*
age:10 id:20
age:30 id:40
age:50 id:60
age:10 id:20
age:30 id:40
age:50 id:60
*/
}
int main()
{
text04();
}