<STL> accumulate 与 自定义数据类型

C++ STL中有一个通用的数值类型计算函数— accumulate(),可以用来直接计算数组或者容器中C++内置数据类型,例如:

 
  
#include < numeric >
int arr[] = { 10 , 20 , 30 , 40 , 50 };
vector
< int > va( & arr[ 0 ], & arr[ 5 ]);
int sum = accumulate(va.begin(),va.end(), 0 ); // sum = 150

但是对于自定义数据类型,我们就需要自己动手写一个类来实现自定义数据的处理,然后让它作为accumulate()的第四个参数,accumulate()的原型为(文件取自DEV-C++编译器):

 
  
1 template < typename _InputIterator, typename _Tp, typename _BinaryOperation >
2 _Tp accumulate(_InputIterator __first, _InputIterator __last, _Tp __init,
3 _BinaryOperation __binary_op)
4 {
5 // concept requirements
6   __glibcxx_function_requires(_InputIteratorConcept < _InputIterator > )
7 __glibcxx_requires_valid_range(__first, __last);
8
9 for ( ; __first != __last; ++ __first)
10 __init = __binary_op(__init, * __first);
11 return __init;
12 }

第四个参数为 __binary_op ,我们需要重写这个函数对象,后面还会继续分析...

假设自定义数据类型为:

 
  
struct Student
{
string name; // 学生姓名
int total; // 四级分数
};

那么我们可能要定义如下列的类:

 
  
class PS{
public :
int operator ()( int t1, const Student & t2)
{
return (t1 + t2.total);
}

};

注意,在类中我们重写了operator(),其中第一参数是int类型,第二个参数是const Student& 类型,为什么第一个参数是int类型呢?我们看一下accumulate()函数的原型,accumulate()函数会将其第三个参数(也就是初始化元素,本例为int类型,因为Student结构中的累加值total为int型),第四个参数为一个指针,会一次遍历容器中的每一个元素,用以实现和前面元素的累加。

完整代码如下:

 
  
#include < iostream >
#include
< algorithm >
#include
< numeric >
#include
< vector >
#include
< string >
using namespace std;

struct Student
{
string name;
int total;
};

class PS{
public :
int operator ()( int t1, const Student & t2)
{
return (t1 + t2.total);
}

};

int main()
{
Student student[
3 ] = {
{
" hicjiajia " , 10 },
{
" sijikaoshi " , 20 },
{
" what " , 40 }
};

int sum = accumulate( & student[ 0 ], & student[ 3 ], 0 ,PS());
cout
<< sum << endl;

system(
" pause " );
return 0 ;
}

以前学编程都是用int类型,那只是理论,而实际编程会遇到各种各样的数据,从实践中我学到了不少~~ 吼吼...

转载于:https://www.cnblogs.com/hicjiajia/archive/2010/12/21/1912218.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值