摘要:本文主要讲了适配器的一些内容,重要的是了解适配器使用的步骤。
1 #include<iostream>
2 #include<vector>
3 #include <algorithm>
4 #include<functional>
5 #include <string>
6
7 using namespace std;
8
9 //第一步 绑定 数据 bind2nd
10 //继承类 binary_function<参数类型1 ,参数类型2 ,返回值类型>
11 //加const修饰 operator()
12 class MyPrint:public binary_function<int,int,void> {
13 public:
14 void operator()(int v,int start)const{
15 cout << v+start << endl;
16 }
17 };
18 void test01() {
19 vector<int>v;
20 for (int i=0;i<10;i++)
21 {
22 v.push_back(i);
23 }
24 cout << "请输入起始值" << endl;
25 int num;
26 cin >> num;
27 for_each(v.begin(), v.end(),bind2nd(MyPrint(),num));
28 }
29
30 class GreaterThenFive :public unary_function<int, bool>
31 {
32 public:
33 bool operator()(int v) const
34 {
35 return v > 5;
36 }
37 };
38
39 void test02() {
40 vector<int>v;
41 for (int i=0;i<10;i++)
42 {
43 v.push_back(i);
44 }
45 vector<int>::iterator pos = find_if(v.begin(), v.end(), not1(GreaterThenFive()));
46 //vector<int>::iterator pos = find_if(v.begin(),v.end(),not1(bind2nd(greater<int>(),5))); //取反适配器,找到的是小于5的数字
47 if (pos!=v.end())
48 {
49 cout << "找到小于5的数" << *pos << endl;
50 }
51 else {
52 cout << "未找到" << endl;
53 }
54 }
55
56 void MyPrint03(int v, int start)
57 {
58 cout << v + start << endl;
59 }
60 //函数指针适配器
61 void test03()
62 {
63 vector<int>v;
64 for (int i = 0; i < 10; i++)
65 {
66 v.push_back(i);
67 }
68 //将函数指针 适配为 函数对象
69 // ptr_fun
70 for_each(v.begin(), v.end(), bind2nd(ptr_fun(MyPrint03), 100));
71 }
72
73 //成员函数适配器
74 class Person
75 {
76 public:
77 Person(string name, int age)
78 {
79 this->m_Name = name;
80 this->m_Age = age;
81 }
82
83 void showPerson()
84 {
85 cout << "成员函数中:姓名: " << m_Name << " 年龄:" << m_Age << endl;
86 }
87 void plusAge()
88 {
89 this->m_Age = this->m_Age + 100;
90 }
91
92 string m_Name;
93 int m_Age;
94 };
95
96 void MyPrintPerson(Person & p)
97 {
98 cout << "姓名: " << p.m_Name << " 年龄:" << p.m_Age << endl;
99 }
100
101 void test04()
102 {
103 vector<Person>v;
104
105 Person p1("aaa", 10);
106 Person p2("bbb", 15);
107 Person p3("ccc", 18);
108 Person p4("ddd", 40);
109
110 v.push_back(p1);
111 v.push_back(p2);
112 v.push_back(p3);
113 v.push_back(p4);
114
115 //成员函数适配器
116 // mem_fun_ref
117 for_each(v.begin(), v.end(), mem_fun_ref(&Person::showPerson));
118 for_each(v.begin(), v.end(), mem_fun_ref(&Person::plusAge));
119 for_each(v.begin(), v.end(), mem_fun_ref(&Person::showPerson));
120 }
121
122 int main() {
123 //test01();
124 //test02();
125 //test03();
126 test04();
127 system("pause");
128 return 0;
129 }