C++的STL中accumulate的用法
来源:互联网 发布:iphone 办公软件 编辑:程序博客网 时间:2024/05/16 08:45
accumulate定义在#include<numeric>中,作用有两个,一个是累加求和,另一个是自定义类型数据的处理
1.累加求和
- int sum = accumulate(vec.begin() , vec.end() , 42);
accumulate带有三个形参:头两个形参指定要累加的元素范围,第三个形参则是累加的初值。
accumulate函数将它的一个内部变量设置为指定的初始值,然后在此初值上累加输入范围内所有元素的值。accumulate算法返回累加的结果,其返回类型就是其第三个实参的类型。
可以使用accumulate把string型的vector容器中的元素连接起来:
- string sum = accumulate(v.begin() , v.end() , string(" "));
2.自定义数据类型的处理
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()的原型为
- template<class _InIt,
- class _Ty,
- class _Fn2> inline
- _Ty _Accumulate(_InIt _First, _InIt _Last, _Ty _Val, _Fn2 _Func)
- { // return sum of _Val and all in [_First, _Last), using _Func
- for (; _First != _Last; ++_First)
- _Val = _Func(_Val, *_First);
- return (_Val);
- }
- #include <vector>
- #include <string>
- using namespace std;
- struct Grade
- {
- string name;
- int grade;
- };
- int main()
- {
- Grade subject[3] = {
- { "English", 80 },
- { "Biology", 70 },
- { "History", 90 }
- };
- int sum = accumulate(subject, subject + 3, 0, [](int a, Grade b){return a + b.grade; });
- cout << sum << endl;
- system("pause");
- return 0;
- }
0 0
- C++的STL中accumulate的用法
- C++的STL中accumulate的用法
- STL中accumulate函数的使用
- STL中accumulate函数的使用
- accumulate的用法
- accumulate的用法
- c++STL之accumulate
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- C++STL中vector容器的用法
- [C++]STL中map的用法
- C++STL中vector容器的用法
- C++ find accumulate count的用法
- C/C++-STL中lower_bound与upper_bound的用法
- 对象类型的转换(向上转型和向下转型)
- (转)Android抽象布局——include、merge 、ViewStub
- Spring的bean的生命周期
- 【Android】状态栏颜色的适配
- Python 学习笔记
- C++的STL中accumulate的用法
- Oracle分析函数之排序值rank()
- 接口
- nginx 静态文件缓存
- Linux下oracle11g静默安装过程
- 搭建高可用mongodb集群(四)—— 分片
- 基于Android的即时通讯应用[使用融云SDK]
- Spring IOC三种注入方式(接口注入、setter注入、构造器注入)
- cvCreateImage函数 给创建图像分配内存、用于灰度化