查找算法find_if自定义数据类型

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Person
{
public:
   Person(string name, int age):
   name(name),
   age(age)
   {}

   string name;
   int age;
};

class Print
{
public:
   void operator()(Person p)
   {
      cout << p.name << " " << p.age << endl;
   }
};

class Find
{
public:
   bool operator()(const Person &p)
   {
      return p.age > 10;
   }
};

int main()
{
   Person p1("furong", 10);
   Person p2("quange", 8);
   Person p3("zhangsan", 20);

   vector<Person> v;
   v.push_back(p1);
   v.push_back(p2);
   v.push_back(p3);

   vector<Person>::iterator it = find_if(v.begin(), v.end(), Find());
   if(it != v.end())
   {
      cout << "找到了" << endl;
      Print()(*it);
   }
   else
   {
      cout << "未找到" << endl;
   }

   return 0;
}
$ ./a.out        
找到了
zhangsan 20
posted @ 2022-07-31 12:47  thomas_blog  阅读(43)  评论(0编辑  收藏  举报