啥是函数符
有定义了operator()()的类
函数符概念
这些都是概念 就是一个称呼
程序示例
#include <iostream>
#include <list>
#include <iterator>
// STL的算法库
#include <algorithm>
template<class T>
class TooBig
{
private:
T cutoff;
public:
TooBig(const T & t) : cutoff(t) {}
// 定义了operator()()
bool operator()(const T & v) {return v > cutoff;}
};
void outint(int n) {std::cout << n << " ";}
int main()
{
using std::list;
using std::cout;
using std::endl;
TooBig<int> f100(100);
int vals[10] = {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};
list<int> yadayada(vals, vals + 10);
list<int> etcetera(vals, vals + 10);
cout << "Original lists:\n";
for_each(yadayada.begin(), yadayada.end(), outint);
cout << endl;
for_each(etcetera.begin(), etcetera.end(), outint);
cout << endl;
// list容器的内置函数 remove_if() 会将容器中的每个元素丢给f100 将f100这个类对象当做函数来调用(类名后面加括号 )这样就调用了operator()函数 返回true的话 就删除元素
yadayada.remove_if(f100);
etcetera.remove_if(TooBig<int>(200));
cout << "Trimmed lists:\n";
for_each(yadayada.begin(), yadayada.end(), outint);
cout << endl;
for_each(etcetera.begin(), etcetera.end(), outint);
cout << endl;
return 0;
}
运行结果
函数适配器
预定义的函数符
就是C++ 内置的函数符
在<functional>中
C++ 针对内置的算术运算符、关系运算符和逻辑运算符 都提供了预定义的函数符
自适应函数符
自适应生成器,自适应一元函数,自适应二元函数,自适应谓词, 自适应二院谓词
自适应函数符中有标识参数类型,返回类型的成员变量result_type, first_argument_type, second_argument_type(二元函数的第二个参数类型名称)
STL内置binder1st和binder2nd类(函数适配器)将二元函数转成一元函数
另一个适配器:
bind1st() 其实就是将binder1st做成匿名函数而已
用法:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <functional>
void Show(double);
const int LIM = 6;
int main()
{
using namespace std;
double arr1[LIM] = {28, 29, 30, 35, 38, 59};
double arr2[LIM] = {63, 65, 69, 75, 80, 99};
vector<double> gr8(arr1, arr1 + LIM);
vector<double> m8(arr2, arr2 + LIM);
cout.setf(ios_base::fixed);
cout.precision(2);
cout << "gr8:\t";
for_each(gr8.begin(), gr8.end(), Show);
cout <<endl;
cout << "m8: \t";
for_each(m8.begin(), m8.end(), Show);
cout <<endl;
vector<double> sum(LIM);
transform(gr8.begin(), gr8.end(), m8.begin(), sum.begin(),
plus<double>());
cout << "sum:\t";
for_each(sum.begin(), sum.end(), Show);
cout << endl;
vector<double> prod(LIM);
transform(gr8.begin(), gr8.end(), prod.begin(),
// 这里使用了bind1st 其实就是建立了类似binder1st()的匿名函数 然后将gr8的每个元素和2.5丢给multiplies对象的operator()
bind1st(multiplies<double>(), 2.5));
cout << "prod:\t";
for_each(prod.begin(), prod.end(), Show);
cout << endl;
return 0;
}
void Show(double v)
{
std::cout.width(6);
std::cout << v << ' ';
}
运行结果
c++11提供了lambda表达式(python的匿名函数标识符么? 不知道 18章会说到)
函数对象完结