C++中accumulate函数的主要用法
一、函数原型
accumulate 函数定义在头文件 numeric 中,其函数原型为:
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);
}
可能有些C++小白看不懂函数原型,不过没关系,接下来我详细讲解一下:
data_T accumulate(iterator_begin,iterator_end,init_val,cmp);
将函数原型简化,
data_T 是数据类型,它作为函数的 返回值类型 可以是int、long long 、double等;iterator_begin 和 iterator_end 分别是起始迭代器和结束迭代器,其范围为 从iterator_begin开始,到iterator_end结束的左闭右开区间 。
init_val 是初始值,
cmp 是自定义回调函数。
accumulate 函数有这四个参数,前三个参数为必要,第四个为非必要。
二、主要用法
1、accumulate 函数的主要用处是对区间元素 累加求和 或其他操作(累乘,倍数等),时间复杂度为 O(n)。
对第四个参数,若不指定,默认为累加操作。
特别需要注意的是函数的返回值类型必须与初始值类型一致,否则会有意想不到的错误。
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 999999;
signed main()
{
vector<int> a(N);
ll sum = 0;
for(int i = 1;i < N;i++)
{
a[i] = N;sum += a[i];
}
ll res1 = accumulate(a.begin() + 1,a.end(),0);
ll res2 = accumulate(a.begin() + 1,a.end(),0ll);
cout << sum << '\n';
cout << res1 << '\n';
cout << res2 << '\n';
}
可以看到返回值类型与初始值类型不一致时,发生错误。
2、除此之外,accumulate 函数还可以通过 回调函数 实现你想进行的操作。另外,accumulate函数对结构体,以及string等类型也是可以使用的。
(1)累乘操作
这里 multiplies<data_T> 是内置累乘回调函数,data_T是元素数据类型。
#include <iostream>
#include <numeric>
using namespace std;
int main() {
vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = accumulate(arr.begin(), arr.end(), 1, multiplies<int>()); // 初值1 * (1 * 2 * 3 * 4 *... * 10)
cout << sum << endl; // 输出3628800
return 0;
}
(2)计算数组中每个元素乘以3后的和
#include <iostream>
#include <numeric>
using namespace std;
int fun(int acc, int num) {//acc为当前的和,num为需要计算的下一个值,返回值由acc接收
return acc + num * 3;
}
int main() {
vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = accumulate(arr.begin(), arr.end(), 0, fun);
cout << sum << endl; // 输出 165
return 0;
}
(3)拼接字符串
#include <iostream>
#include <numeric>
using namespace std;
int main() {
vector<string> words{"this ", "is ", "a ", "sentence!"};
string init = "hello, ";
string res = accumulate(words.begin(), words.end(), init); // 连接字符串,init为字符串的初始值
cout << res << endl; // hello, this is a sentence!
return 0;
}
好了,以上就是accumulate函数的主要内容了,祝各位学习愉快!