-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathaccumulate.cpp
More file actions
55 lines (43 loc) · 1.33 KB
/
accumulate.cpp
File metadata and controls
55 lines (43 loc) · 1.33 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
// Created by pengshuai on 2022/7/24.
//
#include <iostream> // cout
#include <functional> // minus
#include <numeric> // accumulate
using namespace std;
/*
* init 是初始量
* template <class InputIterator, class T>
* T accumulate (InputIterator first, InputIterator last, T init);
*
* binary_op 是二元运算符号,例如 minus<int>()
* template <class InputIterator, class T, class BinaryOperation>
* T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);
* */
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};
cout << "using default accumulate: ";
cout << accumulate(numbers,numbers+3, init);
cout << '\n';
cout << "using functional's minus: ";
cout << accumulate (numbers, numbers+3, init, minus<int>());
cout << '\n';
cout << "using custom function: ";
cout << accumulate (numbers, numbers+3, init, myfunction);
cout << '\n';
cout << "using custom object: ";
cout << accumulate (numbers, numbers+3, init, myobject);
cout << '\n';
return 0;
}
/* 输出结果:
* using default accumulate: 160
* using functional's minus: 40
* using custom function: 220
* using custom object: 280
* */