C++中accumulate的用法

accumulate定义在#include<numeric>中,作用有两个,一个是累加求和,另一个是自定义类型数据的处理

1.累加求和

[cpp] 
  1. int sum = accumulate(vec.begin() , vec.end() , 42);  

accumulate带有三个形参:头两个形参指定要累加的元素范围,第三个形参则是累加的初值。

accumulate函数将它的一个内部变量设置为指定的初始值,然后在此初值上累加输入范围内所有元素的值。accumulate算法返回累加的结果,其返回类型就是其第三个实参的类型。

可以使用accumulate把string型的vector容器中的元素连接起来:

[cpp] 
  1. string sum = accumulate(v.begin() , v.end() , string(" "));  
这个函数调用的效果是:从空字符串开始,把vec里的每个元素连接成一个字符串。

2.自定义数据类型的处理

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

[cpp] 
  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()的原型为

[cpp] 
  1. template<class _InIt,  
  2.     class _Ty,  
  3.     class _Fn2> inline  
  4.     _Ty _Accumulate(_InIt _First, _InIt _Last, _Ty _Val, _Fn2 _Func)  
  5.     {   // return sum of _Val and all in [_First, _Last), using _Func  
  6.     for (; _First != _Last; ++_First)  
  7.         _Val = _Func(_Val, *_First);  
  8.     return (_Val);  
  9.     }  
【例1】

[cpp] 
  1. #include <vector>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. struct Grade  
  6. {  
  7.     string name;  
  8.     int grade;  
  9. };  
  10.   
  11. int main()  
  12. {  
  13.     Grade subject[3] = {  
  14.         { "English", 80 },  
  15.         { "Biology", 70 },  
  16.         { "History", 90 }  
  17.     };  
  18.   
  19.     int sum = accumulate(subject, subject + 3, 0, [](int a, Grade b){return a + b.grade; });  
  20.     cout << sum << endl;  
  21.   
  22.     system("pause");  
  23.     return 0;  
  24. }  

猜你喜欢

转载自blog.csdn.net/qq_40803710/article/details/80273811
今日推荐