1、考虑下面的需求,vector中放置Person,Person有age和name字段。在vector中查找第一个Person c,这个很简单,方法如下:

  vector<Person>::iterator iter = find(personVector.begin(),personVector.end(),c);

  注意:find算法使用操作符==,比较对象是否相等,需要提供==重载。

2、考虑下面的需求,在vector中查找第一个age>15的Person。使用find_if和仿函数。如下:

  iter = find_if(personVector.begin(),personVector.end(),GetBigAgeFunctor(15));

3、完整代码如下:

Person.h

 1 #ifndef PERSON_H__
 2 #define PERSON_H__
 3 
 4 #include <string>
 5 #include <iostream>
 6 using namespace std;
 7 
 8 class Person
 9 {
10 private :
11     int age;
12     string name;
13 
14 public :
15     Person();
16 
17     Person(const int& age,const string& name);
18 
19     int GetAge() const;
20 
21     void SetAge(const int& age);
22 
23     string GetName() const;
24 
25     void SetName(const string& name);
26 
27     bool operator==(const Person& rhs);
28 
29     operator int() const;
30 
31 };
32 #endif
View Code

相关文章:

  • 2022-12-23
  • 2021-11-05
  • 2021-12-20
  • 2021-12-09
  • 2022-12-23
  • 2022-03-10
  • 2022-12-23
猜你喜欢
  • 2022-01-27
  • 2021-10-08
  • 2022-12-23
相关资源
相似解决方案