#include<iostream>
#include<vector>
#include<string>
#include<functional>
#include<algorithm>
using namespace std;
class myPrint :public binary_function<int, int, void> {
public:
void operator()(int val,int start) const
{
cout << "val:" << val <<" start:" << start << " res:" << start + val << endl;
}
};
class GreaterThanFive :public unary_function<int, bool>
{
public:
bool operator()(int val) const
{
return val > 5;
}
};
void myPrint1(int val, int start)
{
cout << val << " " << start << " " << val + start << endl;
}
void test01() {
vector<int> v;
for (int i = 0; i < 10;i++) {
v.push_back(i + 1);
}
//将4通过bind2nd()传入myPrint的operator中为start
for_each(v.begin(), v.end(), bind2nd(myPrint(), 4));
//将8通过bind2nd()传入myPrint的operator中为val
for_each(v.begin(), v.end(), bind1st(myPrint(), 8));
//一元取反
vector<int>::iterator pos1 = find_if(v.begin(), v.end(), not1( GreaterThanFive()));
vector<int>::iterator pos2 = find_if(v.begin(), v.end(), not1(bind2nd(greater<int>(), 5)));
cout << "pos1:" << *pos1 << endl;
cout << "pos2:" << *pos2 << endl;
//二元取反
sort(v.begin(), v.end(), not2(less<int>()));
for_each(v.begin(), v.end(), [](int val) {cout << "val: " << val << endl; });
for_each(v.begin(), v.end(), bind2nd(ptr_fun(myPrint1), 1000));
}
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
void showPerson()
{
cout << "name:" << this->m_Name << " age:" << this->m_Age << endl;
}
void addAge()
{
this->m_Age += 100;
}
string m_Name;
int m_Age;
};
void test02()
{
vector< Person > v;
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 30);
Person p4("ddd", 40);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
for_each(v.begin(), v.end(), mem_fun_ref(&Person::showPerson));
for_each(v.begin(), v.end(), mem_fun_ref(&Person::addAge));
for_each(v.begin(), v.end(), mem_fun_ref(&Person::showPerson));
}
int main() {
test01();
cout << "-------------------------" << endl;
test02();
system("pause");
return EXIT_SUCCESS;
}
val:1 start:4 res:5
val:2 start:4 res:6
val:3 start:4 res:7
val:4 start:4 res:8
val:5 start:4 res:9
val:6 start:4 res:10
val:7 start:4 res:11
val:8 start:4 res:12
val:9 start:4 res:13
val:10 start:4 res:14
val:8 start:1 res:9
val:8 start:2 res:10
val:8 start:3 res:11
val:8 start:4 res:12
val:8 start:5 res:13
val:8 start:6 res:14
val:8 start:7 res:15
val:8 start:8 res:16
val:8 start:9 res:17
val:8 start:10 res:18
pos1:1
pos2:1
val: 10
val: 9
val: 8
val: 7
val: 6
val: 5
val: 4
val: 3
val: 2
val: 1
10 1000 1010
9 1000 1009
8 1000 1008
7 1000 1007
6 1000 1006
5 1000 1005
4 1000 1004
3 1000 1003
2 1000 1002
1 1000 1001
-------------------------
name:aaa age:10
name:bbb age:20
name:ccc age:30
name:ddd age:40
name:aaa age:110
name:bbb age:120
name:ccc age:130
name:ddd age:140
请按任意键继续. . .