#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <string>
using namespace std;
class MyPrint: public binary_function<int, int, void> { // int: 类型 int: 类型 void: 返回值
public:
void operator()(int value, int start) const {
cout << "value: " << value << " start: " << start << " value + start: " << value + start << endl;
}
};
void test01() {
vector<int>vector1;
for (int i = 0; i < 10; i++) {
vector1.push_back(i + 1);
}
int number;
cout << "请输入起始值: ";
cin >> number;
for_each(vector1.begin(), vector1.end(), bind2nd(MyPrint(), number));
for_each(vector1.begin(), vector1.end(), bind1st(MyPrint(), number));
}
class GreaterThenFive: public unary_function<int, bool> {
public:
bool operator()(int value1) const {
return value1 > 5;
}
};
void test02() {
vector<int> vector2;
for (int i = 0; i < 10; i++) {
vector2.push_back(i);
}
//vector<int>::iterator position = find_if(vector2.begin(), vector2.end(), not1(GreaterThenFive()));
vector<int>::iterator position = find_if(vector2.begin(), vector2.end(), not1(bind2nd(greater<int>(), 5)));
if (position != vector2.end()) {
cout << "找到小于5的数字为: " << *position << endl;
} else {
cout << "没有找到";
}
}
void myPrint(int value, int start) {
cout << "value: " << value << " start: " << start << endl;
}
void test03() {
vector<int> vector3;
for (int i = 0; i < 10; i++) {
vector3.push_back(i);
}
for_each(vector3.begin(), vector3.end(), bind2nd(ptr_fun(myPrint), 100));
}
class Person {
public:
Person(string name, int age) {
this->name = name;
this->age = age;
}
void showPerson() {
cout << "name: " << this->name << " age: " << this->age << endl;
}
void plusAge() {
this->age += 100;
}
string name;
int age;
};
void myPrintPerson(Person& person) {
cout << "name: " << person.name << " age: " << person.age << endl;
}
void test04() {
vector<Person> personVector;
Person person1("roger1", 19);
Person person2("roger2", 20);
Person person3("roger3", 21);
Person person4("roger4", 22);
personVector.push_back(person1);
personVector.push_back(person2);
personVector.push_back(person3);
personVector.push_back(person4);
for_each(personVector.begin(), personVector.end(), mem_fun_ref(&Person::showPerson));
for_each(personVector.begin(), personVector.end(), mem_fun_ref(&Person::plusAge));
for_each(personVector.begin(), personVector.end(), mem_fun_ref(&Person::showPerson));
}
int main() {
//test01();
//test02();
//test03();
test04();
return EXIT_SUCCESS;
}