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

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

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

   bool operator==(const Person &p)
   {
      return (p.name == name) && (p.age == age);
   }

   string name;
   int age;
};

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

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(v.begin(), v.end(), p2);
   if(it != v.end())
   {
      cout << "找到了" << endl;
      Print()(*it);
   }
   else
   {
      cout << "未找到" << endl;
   }

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