1 #include<iostream>
2 #include<cstdlib>
3 using namespace std;
4 #include<vector>
5 #include<algorithm>
6 #include<string>
7
8
9 /*
10 5.2.2 find_if
11 按条件查找元素
12 find_if(iterator beg, iterator end, _Pred);
13 // 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
14 // beg 开始迭代器
15 // end 结束迭代器
16 // _Pred 函数或者谓词(返回bool类型的仿函数)
17 find_if按条件查找使查找更加灵活,提供的仿函数可以改变不同的策略
18 */
19
20
21 class Greater5
22 {
23 public:
24 bool operator()(int val) //谓词
25 {
26 return val > 5;
27 }
28 };
29
30
31 void test522() //查找内置数据类型
32 {
33 vector<int> v;
34 for(int i=0; i<10; i++)
35 {
36 v.push_back(i+1);
37 }
38
39 vector<int>::iterator it = find_if(v.begin(), v.end(), Greater5());
40 if(it == v.end())
41 {
42 cout << "未找到" << endl;
43 }
44 else
45 {
46 cout << "找到了:" << *it << endl;
47 }
48 }
49
50
51 class Person
52 {
53 public:
54 string name;
55 int age;
56
57 public:
58 Person(string _name, int _age)
59 {
60 this->name = _name;
61 this->age = _age;
62 }
63 };
64
65
66 class Greater20
67 {
68 public:
69 bool operator()(Person & p) //谓词
70 {
71 return p.age > 20;
72 }
73 };
74
75
76 void test522_2() //查找自定义数据类型
77 {
78 vector<Person> v;
79 Person p1("aaa", 10);
80 Person p2("bbb", 20);
81 Person p3("ccc", 30);
82 Person p4("ddd", 40);
83 v.push_back(p1);
84 v.push_back(p2);
85 v.push_back(p3);
86 v.push_back(p4);
87
88 vector<Person>::iterator it = find_if(v.begin(), v.end(), Greater20());
89 if(it == v.end())
90 {
91 cout << "未找到" << endl;
92 }
93 else
94 {
95 cout << "找到了:" << endl;
96 cout << "name:" << it->name << " age:" << it->age << endl;
97 }
98 }
99
100
101 int main()
102 {
103 test522();
104 test522_2();
105
106 system("pause");
107 return 0;
108 }
