函数对象适配器是完成一些配接工作,这些配接包括绑定(bind),否定(negate),以及对一般函数或成员函数的修饰,使其成为函数对象
bind1st:将参数绑定为函数对象的第一个参数
bind2nd:将参数绑定为函数对象的第二个参数
not1:对一元函数对象取反
not2:对二元函数对象取反
ptr_fun:将普通函数修饰成函数对象
mem_fun:修饰成员函数
mem_fun_ref:修饰成员函数
绑定适配器
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<map>
#include<functional>
#include<algorithm>
using namespace std;
struct MyPrint : public binary_function<int, int, void>
{
void operator()(int v, int w) const
{
cout << "v:" << v << " val:" << w
<< " v + w:"<<v+w << endl;
}
};
void test01(){
vector<int> v;
for (int i = 0; i < 10; i++) {
v.push_back(i);
}
MyPrint print;
int addNum = 100;
for_each(v.begin(), v.end(), bind2nd(print,addNum));
for_each(v.begin(), v.end(), bind1st(print, addNum));
}
int main() {
test01();
return 0;
}
取反适配器
struct MyCompare :public binary_function<int,int ,bool>
{
public:
bool operator()(int v1,int v2) const{
return v1 > v2;
}
};
struct MyPrint2 {
void operator()(int v) const
{
cout << "v:" << v <<endl;
}
};
struct MyGreater : public unary_function<int, bool>
{
bool operator()(int val)const
{
return val < 45;
}
};
void test02() {
vector<int> v;
for (int i = 0; i < 10; i++) {
v.push_back(rand()%100);
}
for_each(v.begin(), v.end(), MyPrint2());
cout << "-----------" << endl;
sort(v.begin(), v.end(), MyCompare());
for_each(v.begin(), v.end(), MyPrint2());
cout << "-----------" << endl;
sort(v.begin(), v.end(), not2(MyCompare()));
for_each(v.begin(), v.end(), MyPrint2());
vector<int>::iterator it = find_if(v.begin(), v.end(), not1(MyGreater()));
cout << (*it) << endl;
}
成员函数适配器
class Person {
public:
Person(int age,int id):mAge(age),mId(id){}
Person(){}
void show() {
cout << "年龄:" << this->mAge << " ID:" << this->mId << endl;
}
int mAge;
int mId;
};
void test04() {
vector<Person> v;
Person p1(10, 20), p2(23, 59), p3(18, 44);
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);
cout << "----------------" << endl;
for_each(v1.begin(), v1.end(), mem_fun(&Person::show));
}