C++总共有5种可调用对象: 普通函数, 函数指针, lambda, 函数对象(仿函数), bind创建的对象(主要将多元谓词降次)
具体代码如下:
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
using namespace std;
using namespace std::placeholders;//can't use std only
const int NUM = 40;
/*c++ has 5 kinds of callable objects*/
//1
auto f = [](int &a) { a = a * a; };//lambda
//2
void callable (int &a, int b)
{
if (a * a < b)// if the square of a is less than b, then square it
{
a = a * a;
}
};
// note: use fuctional header and placeholders namespace before bind
auto call = bind(callable, _1, NUM);//bind
//3
void square(int &a)//ordinary function
{
a = a * a;
}
//4
void(*p)(int &a) = square;//function pointer
auto p1 = □//we can use auto in a easy way: p1 == p
//5
//function object: class that overload the function-call operator
struct PrintInt//function-object or functor
{
void operator()(int elem)
{
cout << elem << " ";
}
};
int main()
{
vector<int> v1{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
vector<int> v2{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
vector<int> v3{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
vector<int> v4{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for_each(v1.begin(), v1.end(), f);
for_each(v2.begin(), v2.end(), square);
for_each(v3.begin(), v3.end(), p);
//for_each(v3.begin(), v3.end(), p1);
for_each(v4.begin(), v4.end(), call);
for_each(v3.crbegin(), v3.crend(), [](int elem) { cout << elem << " "; });
cout << endl;
for_each(v3.cbegin(), v3.cend(), PrintInt());//don't lose "()"
cout << endl;
for_each(v4.cbegin(), v4.cend(), PrintInt());
cout << endl;
return 0;
}