18.2.1【STL常用查找算法find】
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 常用查找算法 11 12 find //查找元素 13 find_if //按条件查找元素 14 adjacent_find //查找相邻重复元素 15 binary_search //二分查找法 16 count //统计元素个数 17 count_if //按条件统计元素个数 18 19 5.2.1 find 20 查找指定元素,找到返回指定元素的迭代器,找不到返回结束迭代器end() 21 find(iterator beg, iterator end, value); 22 // 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置 23 // beg 开始迭代器 24 // end 结束迭代器 25 // value 查找的元素 26 */ 27 28 29 void test521() //查找内置数据类型 30 { 31 vector<int> v; 32 for(int i=0; i<10; i++) 33 { 34 v.push_back(i); 35 } 36 37 vector<int>::iterator it = find(v.begin(), v.end(), 5); 38 if(it == v.end()) 39 { 40 cout << "未找到" << endl; 41 } 42 else 43 { 44 cout << "找到了:" << *it << endl; 45 } 46 } 47 48 49 class Person 50 { 51 public: 52 string name; 53 int age; 54 55 public: 56 Person(string _name, int _age) 57 { 58 this->name = _name; 59 this->age = _age; 60 } 61 62 //重载==使find()知道如何对比Person数据类型 63 bool operator==(const Person & p) 64 { 65 if(this->name == p.name && this->age == p.age) 66 { 67 return true; 68 } 69 return false; 70 } 71 72 }; 73 74 75 void test521_2() //查找自定义数据类型 76 { 77 vector<Person> v; 78 Person p1("aaa", 10); 79 Person p2("bbb", 20); 80 Person p3("ccc", 30); 81 Person p4("ddd", 40); 82 v.push_back(p1); 83 v.push_back(p2); 84 v.push_back(p3); 85 v.push_back(p4); 86 87 Person pp("bbb", 20); 88 vector<Person>::iterator it = find(v.begin(), v.end(), pp); //直接查找会报错,需要重载== 89 if(it == v.end()) 90 { 91 cout << "未找到" << endl; 92 } 93 else 94 { 95 cout << "找到了:"; 96 cout << "name:" << it->name << " age:" << it->age << endl; 97 } 98 } 99 100 101 int main() 102 { 103 test521(); 104 test521_2(); 105 106 system("pause"); 107 return 0; 108 }