1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| #include <iostream> #include <algorithm> #include <vector> #include <functional>
using namespace std;
class Person {
public:
Person(string name, int age) { this->name = name; this->age = age; }
string getName() const { return this->name; }
int getAge() const { return this->age; }
bool operator==(const Person &p) { return this->name == p.name && this->age == p.age; }
private :
string name; int age;
};
class MyPersonCompare : public binary_function<Person *, Person *, bool> {
public:
bool operator()(Person *p1, Person *p2) const { return p1->getName() == p2->getName() && p1->getAge() == p2->getAge(); }
};
bool MyCompare(Person &p) { return p.getName() == "Peter" && p.getAge() == 18; }
void test01() { vector<Person> v;
Person p1("Jim", 15); Person p2("Peter", 18); Person p3("David", 16); Person p4("Tom", 20);
v.push_back(p1); v.push_back(p2); v.push_back(p3); v.push_back(p4);
vector<Person>::iterator pos = find_if(v.begin(), v.end(), MyCompare); if (pos != v.end()) { cout << "found person for " << pos->getName() << ", age is " << pos->getAge() << endl; } else { cout << "not found person" << endl; } }
void test02() { vector<Person *> v;
Person p1("Jim", 15); Person p2("Peter", 18); Person p3("David", 16); Person p4("Tom", 20);
v.push_back(&p1); v.push_back(&p2); v.push_back(&p3); v.push_back(&p4);
Person *p5 = new Person("David", 16);
vector<Person *>::iterator pos = find_if(v.begin(), v.end(), bind2nd(MyPersonCompare(), p5)); if (pos != v.end()) { cout << "found person for " << (*pos)->getName() << ", age is " << (*pos)->getAge() << endl; } else { cout << "not found person" << endl; } }
int main() { test01(); test02(); return 0; }
|