C++ //常用查找算法 find //自定义类型需要重载 ==
1 //常用查找算法 find 2 #include<iostream> 3 #include<algorithm> 4 #include<functional> 5 #include<vector> 6 #include<string> 7 #include<map> 8 9 using namespace std; 10 11 //内置数据类型 12 void test01() 13 { 14 vector<int>v; 15 v.push_back(10); 16 v.push_back(20); 17 v.push_back(30); 18 v.push_back(40); 19 v.push_back(50); 20 21 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 22 { 23 cout << *it << " "; 24 } 25 cout << endl; 26 vector<int>::iterator findpos= find(v.begin(),v.end(),50); 27 28 if (findpos == v.end()) 29 { 30 cout << "没有找到!" << endl; 31 32 } 33 else 34 { 35 cout << "找到了" << endl; 36 cout << *findpos << endl; 37 } 38 39 } 40 41 class Person 42 { 43 public: 44 Person(string name, int age) 45 { 46 this->m_Name = name; 47 this->m_Age = age; 48 } 49 //重载 == 底层find知道如何对比Person数据类型 50 bool operator==(const Person& p) 51 { 52 if (this->m_Name == p.m_Name && this->m_Age == p.m_Age) 53 { 54 return true; 55 } 56 else 57 { 58 return false; 59 } 60 } 61 62 63 string m_Name; 64 int m_Age; 65 }; 66 67 68 //查找自定义 要重载 69 void test02() 70 { 71 vector<Person>v2; 72 73 74 Person p1("张三", 10); 75 Person p2("李四", 20); 76 Person p3("王五", 30); 77 Person p4("赵六", 40); 78 79 v2.push_back(p1); 80 v2.push_back(p2); 81 v2.push_back(p3); 82 v2.push_back(p4); 83 84 Person pp("李四",20); 85 86 vector<Person>::iterator it = find(v2.begin(), v2.end(), pp); 87 88 89 if (it == v2.end()) 90 { 91 cout << "没有找到!" << endl; 92 } 93 else 94 { 95 cout << "找到了!" << endl; 96 cout << "姓名:" << it->m_Name << "\t年龄:" << it->m_Age << endl; 97 } 98 99 100 101 } 102 103 104 105 int main() 106 { 107 108 test01(); 109 test02(); 110 111 system("pause"); 112 return 0; 113 }
本文来自博客园,作者:Bytezero!,转载请注明原文链接:https://www.cnblogs.com/Bytezero/p/15155267.html