// 这些都是仿函数,已经实现了重载小括号的功能
//头文件:#include <functional>
template<class T> T plus<T>
template<class T> T minus<T>
template<class T> T multiplies<T>
template<class T> T divides<T>
template<class T> T modulus<T>
template<class T> T negate<T> // 取反
template<class T> bool equal_to<T>
template<class T> bool not_equal_to<T>
template<class T> bool greater<T>
template<class T> bool greater_equal<T>
template<class T> bool less<T>
template<class T> bool less_equal<T>
template<class T> bool logical_and<T>
template<class T> bool logical_or<T>
template<class T> bool logical_not<T>
negate<int> n;
cout << n(10); << endl; // 输出:-10
plus<int> p;
cout << p(1, 1) << endl;
vector<int> v;
sort(v.begin(), v.end(), greater<int>());
for_each(v.begin(), v.end(), [](int val) {cout << val << " ";});
#include <functional>
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
int num;
cin >> num;
for_each(v.begin(), v.end(), bind2nd(MyPrint(), num));
class MyPrint::public binary_function<int, int, void> {
public:
void operator() (int val, int start) {
cout << val + start << endl;
}
};
// 函数适配器
// 第一步:绑定数据 bind2nd
// 第二步:继承类 binary_function<参数类型1,参数类型2,返回值类型>
// 第三步:加const修饰 operator()
// 适配器,适配原有只有一参数的函数扩展为两个参数
// 取反适配器
// 一元取反, 使用not1
// 要继承 unary_function<参数类型,返回值类型>
// 加上const修饰
vector<int> v;
for (int i = 0; i < 10; i++) {
v.push_back(i);
}
class GreaterThan5: public unary_function<int, bool> {
public:
bool operator()(int v) const {
return v > 5;
}
};
// 查找大于5的数字,需求改为找小于5的数字
vector<int>::iterator pos = find_if(v.begin(), v.end(), not1(GreaterThan5())); // not1表示一元取反,not2表示二元取反
vector<int>::iterator pos = find_if(v.begin(), v.end(), not1(bind2nd(greater<int>(), 5))); // not1表示一元取反,not2表示二元取反
if (pos != v.end()) {
cout << *pos << endl;
}
else {
cout << "not found" << endl;
}
// 函数指针适配器
void MyPrint(int v, int start) {
cout << v + start << endl;
}
for_each(v.begin(), v.end(), bind2nd(ptr_fun(MyPrint), 100));
// 成员函数适配器
class Person {
public:
Person(string name, int age) {
this->m_Name = name;
this->m_Age = age;
}
void showPerson() {
cout << m_Name << m_Age << endl;
}
void plusAge() {
m_Age+=100;
}
string m_Name;
int m_Age;
};
void MyPrintPerson(Person& p) {
cout << p.m_Name << p.m_Age << endl;
}
vector<Person> v;
Person p1("aaa", 10);
Person p2("bbb", 15);
Person p3("ccc", 18);
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(), MyPrintPerson);
for_each(v.begin(), v.end(), mem_fun_ref(&Persion::showPerson));
for_each(v.begin(), v.end(), mem_fun_ref(&Persion::plusAge));// 这个可以实现所有成员年龄增加100岁