accumulate函数

被定义在中,第一个作用为累加求和,另一个作用为对自定义类型数据的处理

累加求和

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

带有三个参数,前两个形参指定哟啊累加的元素范围,第三个形参则是累加的初值

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

自定义数据类型的处理

可以用来直接计算数组或者容器中C++内置数据类型,例如:

1
2
3
4
#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()的原型为

1
2
3
4
5
6
7
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);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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;
}

reduce函数

累加求和,它是 std::accumulate 的泛化版本,它元素的累加顺序没有要求,因此可以用于并行累加。另外也可以通过重载运算符进行累乘等运算。

用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
#include <numeric>
#include <execution>

//通过重载 + 运算符,实现自定义类型的累加操作
struct Foo {
std::string sound = "Foo";
Foo operator+(const Foo& right) const {
return {sound+right.sound};
}
};

int main() {
std::vector<Foo> data(2, Foo{});
Foo final_Foo = std::reduce(data.begin(), data.end());

std::cout << "final_Foo.sound == " << final_Foo.sound << "\n";
//final_Foo.sound == FooFooFoo
}