C++ //常用查找算法 find_if

  1 //常用查找算法   find_if
  2 #include<iostream>
  3 #include<string>
  4 #include<vector>
  5 #include<algorithm>
  6 
  7 using namespace std;
  8 
  9 //内置数据类型
 10 
 11 class GreateFive
 12 {
 13 public:
 14     bool operator()(int val)
 15     {
 16         return val > 5;
 17     }
 18 };
 19 
 20 void test01()
 21 {
 22     vector<int>v;
 23     for (int i = 0; i < 10; i++)
 24     {
 25         v.push_back(i);
 26     }
 27     vector<int>::iterator it = find_if(v.begin(), v.end(), GreateFive());
 28     
 29     if (it == v.end())
 30     {
 31         cout << "没找到!!!" << endl;
 32     }
 33     else
 34     {
 35         cout << "找到了大于5的数字!!" << *it << endl;
 36     }
 37 
 38 }
 39 
 40 //自定义数据类型
 41 
 42 
 43 
 44 class Person
 45 {
 46 public:
 47 
 48     Person(string name, int age)
 49     {
 50         this->m_Name = name;
 51         this->m_Age =age;
 52     }
 53 
 54     
 55 
 56     string m_Name;
 57     int m_Age;
 58 };
 59 
 60 class Greatetwenty
 61 {
 62 public:
 63     bool operator()(Person& p) 
 64     {
 65         return p.m_Age > 20;
 66     }
 67 };
 68 
 69 void test02()
 70 {
 71     vector<Person>v1;
 72     Person p1("张三", 20);
 73     Person p2("李四", 30);
 74     Person p3("王五", 40);
 75     Person p4("赵六", 50);
 76 
 77     v1.push_back(p1);
 78     v1.push_back(p2);
 79     v1.push_back(p3);
 80     v1.push_back(p4);
 81     vector<Person>::iterator it = find_if(v1.begin(), v1.end(), Greatetwenty());
 82 
 83     if (it == v1.end())
 84     {
 85         cout << "没有找到的!!" << endl;
 86     }
 87     else
 88     {
 89         cout << "找到了!!"  << it->m_Name << it->m_Age << endl;
 90     }
 91     
 92 }
 93 
 94 
 95 int main()
 96 {
 97     
 98     test01();
 99 
100     test02();
101 
102     system("pause");
103 
104     return 0;
105 }

 

posted on 2021-08-18 10:37  Bytezero!  阅读(220)  评论(0编辑  收藏  举报