C++ std::accumulate函数用法

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

默认累加求和

1
2
template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );

自定义对数据的处理

1
2
3
template< class InputIt, class T, class BinaryOperation >
constexpr T accumulate( InputIt first, InputIt last, T init,
BinaryOperation op );

参数

first, last: 要求和的元素范围

init:和的初值

op:被使用的二元函数对象。接收当前积累值 a (初始化为 init )和当前元素 b 的二元运算符。

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// accumulate example
#include <iostream> // std::cout
#include <functional> // std::minus
#include <numeric> // std::accumulate

int myfunction (int x, int y) {return x+2*y;}
struct myclass {
int operator()(int x, int y) {return x+3*y;}
} myobject;

int main () {
int init = 100;
int numbers[] = {10,20,30};

std::cout << "using default accumulate: ";
std::cout << std::accumulate(numbers,numbers+3,init);
std::cout << '\n';

std::cout << "using functional minus: ";
std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());
std::cout << '\n';

std::cout << "using custom function: ";
std::cout << std::accumulate(numbers, numbers + 3, 0, [](int a, Grade b){return a + b * 2; });
std::cout << '\n';

std::cout << "using custom object: ";
std::cout << std::accumulate (numbers, numbers+3, init, myobject);
std::cout << '\n';

return 0;
}

输出

1
2
3
4
using default accumulate: 160
using functional minus: 40
using custom function: 120
using custom object: 280

转载自C++ Lambda表达式的基本使用


C++ std::accumulate函数用法
https://gstarmin.github.io/2023/02/24/Cpp-accumulate函数用法/
作者
Starmin
发布于
2023年2月24日
许可协议