Website Summary Files Commits Branches @commit @diff @stats
path: root / Week05 / Exercise01 / NumSeries.cpp
blob: be8c816426b2cab23c8867be1a1302c528a43c0a (plain) (blame)
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
#include "NumSeries.h"
#include <cmath>

void NumSeries::free() {
	delete[] numbers;
}

void NumSeries::copyFrom(const NumSeries& other) {
	allocated = other.allocated;
	size = other.size;

	numbers = new double[allocated];
	for (unsigned i = 0; i < size; ++i)
		numbers[i] = other.numbers[i];
}

void NumSeries::resize() {
	allocated *= 2;

	double* newNumbers = new double[allocated];
	for (unsigned i = 0; i < size; ++i)
		newNumbers[i] = numbers[i];

	delete[] numbers;
	numbers = newNumbers;
}

NumSeries::NumSeries() {
	numbers = nullptr;
	allocated = size = 0;
}

NumSeries::~NumSeries() {
	free();
}

NumSeries::NumSeries(const NumSeries& other) {
	copyFrom(other);
}

NumSeries& NumSeries::operator=(const NumSeries& other) {
	if (this != &other) {
		free();
		copyFrom(other);
	}
	return *this;
}

NumSeries::NumSeries(NumSeries&& other) {
	numbers = other.numbers;
	allocated = other.allocated;
	size = other.size;

	other.numbers = nullptr;
	other.allocated = 0;
	other.size = 0;
}

NumSeries& NumSeries::operator=(NumSeries&& other) {
	if (this != &other) {
		free();

		numbers = other.numbers;
		allocated = other.allocated;
		size = other.size;

		other.numbers = nullptr;
		other.allocated = 0;
		other.size = 0;
	}
	return *this;
}

void NumSeries::Push(double element) {
	if (size >= allocated)
		resize();
	numbers[size++] = element;
}

double NumSeries::At(unsigned index) const {
	if (index >= size)
		return NAN;
	return numbers[index];
}

unsigned NumSeries::Length() const {
	return size;
}