常用算法

STL提供了accumulate函数的一个更为通用的版本。其定义如下:

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()获得的。

使用以类的形式定义的函数对象比普通函数优越,它可以携带更多额外的信息(可以静态数据成员的形式),以后再举例子。

转载于:https://www.cnblogs.com/kevinmeng/archive/2009/07/05/1517136.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值