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