-
Notifications
You must be signed in to change notification settings - Fork 0
/
Averager.cpp
65 lines (57 loc) · 1.69 KB
/
Averager.cpp
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
#include <stdexcept>
#include "Averager.h"
template <typename T>
Averager<T>::Averager(int sampleSize) : pos(0), sampleSize(sampleSize) {
if (sampleSize <= 0) {
throw std::invalid_argument("sampleSize must be greater than 0");
}
sum = std::make_unique<T[]>(sampleSize);
}
template <typename T>
Averager<T>::Averager(const Averager& other)
: pos(other.pos), sampleSize(other.sampleSize), sum(std::make_unique<T[]>(other.sampleSize)) {
std::copy(other.sum.get(), other.sum.get() + other.sampleSize, sum.get());
}
template <typename T>
Averager<T>::Averager(Averager&& other) noexcept
: pos(other.pos), sampleSize(other.sampleSize), sum(std::move(other.sum)) {
other.pos = 0;
other.sampleSize = 0;
}
template <typename T>
Averager<T>& Averager<T>::operator=(const Averager& other) {
if (this != &other) {
pos = other.pos;
sampleSize = other.sampleSize;
sum = std::make_unique<T[]>(other.sampleSize);
std::copy(other.sum.get(), other.sum.get() + other.sampleSize, sum.get());
}
return *this;
}
template <typename T>
Averager<T>& Averager<T>::operator=(Averager&& other) noexcept {
if (this != &other) {
pos = other.pos;
sampleSize = other.sampleSize;
sum = std::move(other.sum);
other.pos = 0;
other.sampleSize = 0;
}
return *this;
}
template <typename T>
void Averager<T>::add(T value) {
sum[pos++] = value;
if (pos >= sampleSize) {
pos = 0;
}
}
template <typename T>
T Averager<T>::getAverage() {
T average = 0;
for (int i = 0; i < sampleSize; i++) {
average += sum[i];
}
return average / sampleSize;
}
template class Averager<long>;