-
Notifications
You must be signed in to change notification settings - Fork 0
/
numeric.h
98 lines (82 loc) · 2.65 KB
/
numeric.h
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#pragma once
/*********************************
*The header contains Numeric Algorithm
*accumlate();innner_product();partial_sum();adjacent_difference()
*********************************/
#include "iterator.h"
namespace mystl {
//accumlate
template <class InputIterator, class T>
T accumlate(InputIterator beg, InputIterator end, T init) {
for (; beg != end; ++beg) {
init += *beg;
}
return init;
}
template <class InputIterator, class T, class BinaryOperator>
T accumlate(InputIterator beg, InputIterator end, T init, BinaryOperator binary_op) {
init = binary_op(init, *beg);
return init;
}
//inner_product
template <class InputIterator, class T>
T inner_product(InputIterator beg1, InputIterator end, InputIterator beg2, T init) {
for (; beg1 != end; ++beg1, ++beg2) {
init += ((*beg1) * (*beg2));
}
return init;
}
template <class InputIterator, class T, class BinaryOperator>
T inner_product(InputIterator beg1, InputIterator end, InputIterator beg2, T init,
BinaryOperator op1, BinaryOperator op2) {
for (; beg1 != end; ++beg1, ++beg2) {
init = op1(init, op2(*beg1, *beg2));
}
}
//partial_sum
template <class InputIterator, class OutputIterator>
OutputIterator partial_sum(InputIterator sourceBeg, InputIterator sourceEnd, OutputIterator destBeg) {
if (sourceBeg == sourceEnd)
*destBeg = *sourceBeg;
auto value = *sourceBeg;
while (++sourceBeg != sourceEnd) {
value += *sourceBeg;
*++destBeg = value;
}
return ++destBeg;
}
template <class InputIterator, class OutputIterator, class BinaryFun>
OutputIterator partial_sum(InputIterator sourceBeg, InputIterator sourceEnd, OutputIterator destBeg,BinaryFun op) {
if (sourceBeg == sourceEnd)
*destBeg = *sourceBeg;
auto value = *sourceBeg;
while (++sourceBeg != sourceEnd) {
value = op(value,*sourceBeg);
*++destBeg = value;
}
return ++destBeg;
}
//adjacent_difference
template <class InputIterator, class OutputIterator>
OutputIterator adjacent_difference(InputIterator sourceBeg, InputIterator sourceEnd, OutputIterator destBeg) {
if (sourceBeg == sourceEnd)
*destBeg = *sourceBeg;
auto value = *sourceBeg;
while (++sourceBeg != sourceEnd) {
value = value - *sourceBeg;
*++destBeg = value;
}
return ++destBeg;
}
template <class InputIterator, class OutputIterator, class BinaryFun>
OutputIterator adjacent_difference(InputIterator sourceBeg, InputIterator sourceEnd, OutputIterator destBeg, BinaryFun op) {
if (sourceBeg == sourceEnd)
*destBeg = *sourceBeg;
auto value = *sourceBeg;
while (++sourceBeg != sourceEnd) {
value = op(value, *sourceBeg);
*++destBeg = value;
}
return ++destBeg;
}
}