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

2022/8/1 1:23:57

本文主要是介绍查找算法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


这篇关于查找算法find_if自定义数据类型的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程