1 #include<iostream>
2 #include<cstdlib>
3 using namespace std;
4 #include<functional>
5 #include<vector>
6 #include<algorithm>
7
8
9 /*
10 4.3 内建函数对象
11
12 4.3.1 内建函数对象意义
13
14 概念:
15 内建了一些函数对象
16 分类:
17 算术仿函数
18 关系仿函数
19 逻辑仿函数
20 用法:
21 这些仿函数所产生的对象,用法和一般函数完全相同
22 使用内建函数对象,需要引入头文件 #include<functional>
23
24 4.3.2 算术仿函数
25
26 template<class T> T plus<T> //加法仿函数
27 template<class T> T minus<T> //减法仿函数
28 template<class T> T multiplies<T> //乘法仿函数
29 template<class T> T divides<T> //除法仿函数
30 template<class T> T modulus<T> //取模仿函数
31 template<class T> T negate<T> //取反仿函数(注意,此仿函数是一元运算,以上其余仿函数均为二元运算)
32
33 4.3.3 关系仿函数
34
35 template<class T> bool equal_to<T> //等于
36 template<class T> bool not_equal_to<T> //不等于
37 template<class T> bool greater<T> //大于
38 template<class T> bool greater_equal<T> //大于等于
39 template<class T> bool less<T> //小于
40 template<class T> bool less_equal<T> //小于等于
41
42 4.3.4 逻辑仿函数
43
44 template<class T> bool logical_and<T> //逻辑与
45 template<class T> bool logical_or<T> //逻辑或
46 template<class T> bool logical_not<T> //逻辑非
47 */
48
49
50 void test432()
51 {
52 negate<int> n;
53 cout << n(50) << endl; //-50
54
55 plus<int> p;
56 cout << p(10, 10) << endl; //20
57 }
58
59
60 class MySort
61 {
62 public:
63 bool operator()(int num1, int num2)
64 {
65 return num1 > num2;
66 }
67 };
68
69
70
71 void test433()
72 {
73 vector<int> v;
74 v.push_back(30);
75 v.push_back(10);
76 v.push_back(20);
77 v.push_back(50);
78 v.push_back(40);
79
80 for(vector<int>::iterator it=v.begin(); it!=v.end(); it++)
81 {
82 cout << *it << " ";
83 }
84 cout << endl;
85
86 //降序
87 //sort(v.begin(), v.end(), MySort()); // 自己实现仿函数
88 sort(v.begin(), v.end(), greater<int>()); //STL内建仿函数,效果同上
89
90 for(vector<int>::iterator it=v.begin(); it!=v.end(); it++)
91 {
92 cout << *it << " ";
93 }
94 cout << endl;
95 }
96
97
98 void test434()
99 {
100 vector<bool> v;
101 v.push_back(true);
102 v.push_back(false);
103 v.push_back(true);
104 v.push_back(false);
105
106 for(vector<bool>::iterator it=v.begin(); it!=v.end(); it++)
107 {
108 cout << *it << " ";
109 }
110 cout << endl;
111
112 //利用逻辑非 将容器v中的数据复制到容器v2中,并执行取反操作
113 vector<bool> v2;
114 v2.resize(v.size());
115 transform(v.begin(), v.end(), v2.begin(), logical_not<bool>()); //transform需要algorithm头文件
116
117 for(vector<bool>::iterator it=v2.begin(); it!=v2.end(); it++)
118 {
119 cout << *it << " ";
120 }
121 cout << endl;
122 }
123
124
125 int main()
126 {
127 test432();
128 test433();
129 test434();
130
131 system("pause");
132 return 0;
133 }
