查找算法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 @   thomas_blog  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示