常用算法
template <typename InputIterator,typename T,typename BinaryOperation>
T accumulate(InputIterator first,InputIterator last,
T init,BinaryOperation binary_op)
{
while (first!=last)
{
init=binary_op(init,*first);
++first;
}
return init;
}
上面的定义没有定义+运算符,而是引入了另一个参数binary_op,作为定义在序列质类型上的二元操作符。
示例:使用增强版的accumulate计算连乘积
#include<iostream>
#include<vector>
#include<cassert>
#include<numeric> //for accumulate
using namespace std;
int mult(int x,int y){return x*y;}
int main()
{
int x[5]={2,3,5,7,11};
vector<int> vector1(&x[0],&x[5]);
int product=
accumulate(vector1.begin(),vector1.end(),1,mult);
assert(product==2310);
cout<<"--OK."<<endl;
return 0;
}
这里传递给accumulate函数的是一个普通函数的mult,实际上传递的是该函数的地址。
函数对象是一种实体,可以不带参数,也可以带有一个以上的参数,不能够从中获得一个值或者改变程序的状态。除了上面所示的普通函数,另一类函数对象是类或者结构的对象,且在其定义中重载了()运算符,而且这种方式在STL中更为常用。
请看下例:
#include<iostream>
#include<vector>
#include<cassert>
#include<numeric> //for accumulate
using namespace std;
class multiply
{
public:
int operator()(int x,int y) const{return x*y;}
};
int main()
{
int x[5]={2,3,5,7,11};
vector<int> vector1(&x[0],&x[5]);
int product=
accumulate(vector1.begin(),vector1.end(),1,multiply());
assert(product==2310);
cout<<"--OK."<<endl;
return 0;
}
通过在类multiply中定义运算符operator(),就定义了一种可以作为函数参数的对象,可以像使用函数一样使用这种对象。这里传递给accumulate的对象是通过调用multiply类的默认构造函数multiply()获得的。
使用以类的形式定义的函数对象比普通函数优越,它可以携带更多额外的信息(可以静态数据成员的形式),以后再举例子。