accumulate与自定义数据类型

C++ STL中有一个通用的数值类型计算函数— accumulate(),可以用来直接计算数组或者容器中C++内置数据类型,例如:
[html]  view plain copy
  1. #include <numeric>  
  2. int arr[]={10,20,30,40,50};  
  3. vector<int> va(&arr[0],&arr[5]);  
  4. int sum=accumulate(va.begin(),va.end(),0);  //sum = 150  

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

[html]  view plain copy
  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 ,我们需要重写这个函数对象,后面还会继续分析...

假设自定义数据类型为:

[html]  view plain copy
  1. struct Student  
  2. {  
  3.       string name;   // 学生姓名  
  4.        int total;      // 四级分数  
  5. };  
那么我们可能要定义如下列的类:
[html]  view plain copy
  1. #include <iostream>  
  2. #include <algorithm>  
  3. #include <numeric>  
  4. #include <vector>  
  5. #include <string>  
  6. using namespace std;  
  7.   
  8. struct Student  
  9. {  
  10.        string name;  
  11.        int total;  
  12. };  
  13.   
  14. class PS{  
  15.  public:  
  16.         int operator()(int t1,const Student& t2)  
  17.         {  
  18.             return (t1 + t2.total);  
  19.         }  
  20.           
  21. };  
  22.   
  23. int main()  
  24. {  
  25.     Student student[3]={  
  26.             {"hicjiajia",10},  
  27.             {"sijikaoshi",20},  
  28.             {"what",40}  
  29.             };  
  30.       
  31.     int sum=accumulate(&student[0],&student[3],0,PS());  
  32.     cout<<sum<<endl;  
  33.       
  34.     system("pause");  
  35.     return 0;  
  36. }  
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值