函数对象适配器

#include
#include
#include
#include
#include
#include
#include
using namespace std;
//函数对象适配器bind1st,bind2nd
struct MyPrint :public binary_function//binary_function<参数类型,参数类型,返回值类型>
{
void operator()(int v1, int v2) const
{
cout << v1 + v2 << endl;
}
};
void test0()
{
vector v;
int i;
for (i = 0;i < 10;i++)
{
v.push_back(i);
}
for_each(v.begin(), v.end(), bind2nd(MyPrint(), 10));//vector元素,加10后输出
//bind2nd,将参数绑定为函数对象的第二个参数
//bind1st,将参数绑定为函数对象的第一个参数
}
//函数对象适配器not1,not2
struct Myprint
{
void operator()(int a) const
{
cout << a << endl;
}
};
void test1()
{
vector v;
v.push_back(3);v.push_back(5);v.push_back(1);v.push_back(4);v.push_back(6);v.push_back(2);
vector::iterator it = find_if(v.begin(), v.end(), not1(bind2nd(less_equal(), 2)));
cout << *it << endl;
sort(v.begin(), v.end(), not2(greater()));
//not1对一元函数对象取反
//not2对二元函数对象取反
for_each(v.begin(), v.end(), Myprint());
}
//给一个普通函数使用绑定适配器
void fun(int v1, int v2)
{
cout << v1 + v2 << endl;
}
void test2()
{
vector v;
v.push_back(2);v.push_back(1);v.push_back(4);v.push_back(6);v.push_back(3);
for_each(v.begin(), v.end(), bind2nd(ptr_fun(fun), 10));//ptr_fun将普通函数转变为函数对象
}
//指定某个成员函数处理成员数据
class Person
{
private:
string name;
int age;
public:
Person(string name, int age)
{
this->name = name;
this->age = age;
}
void printPerson()
{
cout << this->name << ":" << this->age << endl;
}
};
void test3()
{
vector v;
v.push_back(Person("liming", 20));v.push_back(Person("zhaohong", 21));
v.push_back(Person("liguan", 19));v.push_back(Person("wangfei", 20));
for_each(v.begin(), v.end(), mem_fun_ref(&Person::printPerson));//如果vector中存储的是对象,则用mem_fun_ref
//如果vector中存储的是指针,则用mem_fun
}
int main()
{
test0();
test1();
test2();
test3();
system("pause");
return 0;
}

你可能感兴趣的:(C++)