1 #include<iostream>
2 #include<cstdlib>
3 using namespace std;
4 #include<vector>
5 #include<algorithm>
6
7
8 /*
9 4.2 谓词
10
11 4.2.1 谓词概念
12 返回bool类型的仿函数称为谓词(函数对象/仿函数 返回值类型是bool 则称为谓词)
13 如果operator()接受一个参数,那么叫做一元谓词
14 如果operator()接受两个参数,那么叫做二元谓词
15
16 4.2.2 一元谓词
17 4.2.3 二元谓词
18 */
19
20
21 class Greater5
22 {
23 public:
24 bool operator()(int num) //一元谓词:bool + 一参
25 {
26 return num > 5;
27 }
28 };
29
30
31 void test422()
32 {
33 vector<int> v;
34 for(int i=0; i<10; i++)
35 {
36 v.push_back(i);
37 }
38
39 //查找容器中是否存在大于5的数据
40 vector<int>::iterator it = find_if(v.begin(), v.end(), Greater5()); //Greater5()是匿名函数对象,find_if需要引用algorithm头文件
41 if(it == v.end())
42 {
43 cout << "未找到" << endl;
44 }
45 else
46 {
47 cout << "找到了:" << *it << endl;
48 }
49 }
50
51
52 class MySort
53 {
54 public:
55 bool operator()(int num1, int num2) //二元谓词:bool + 二参
56 {
57 //降序:令 前一数 > 后一数
58 return num1 > num2;
59 }
60 };
61
62
63 void test423()
64 {
65 vector<int> v;
66 v.push_back(10);
67 v.push_back(50);
68 v.push_back(20);
69 v.push_back(40);
70 v.push_back(30);
71
72 for(vector<int>::iterator it=v.begin(); it!=v.end(); it++)
73 {
74 cout << *it << " ";
75 }
76 cout << endl;
77
78 sort(v.begin(), v.end()); //该算法默认升序
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()); //MySort()匿名函数对象
88
89 for(vector<int>::iterator it=v.begin(); it!=v.end(); it++)
90 {
91 cout << *it << " ";
92 }
93 cout << endl;
94 }
95
96
97 int main()
98 {
99 test422();
100 test423();
101
102 system("pause");
103 return 0;
104 }
