Website Summary Files Commits Branches @commit @diff @stats
path: root / src / List / List.cpp
blob: bdb9b4a5a2fd4584a9ef683d606ea1af753e8cb6 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include "List.h"

/* Private */

template <class T>
void List<T>::resize() {
	length <<= 1;
	T* temp = new T[length];
	for (int i = 0; i < count; i++)
		temp[i] = elements[i];
	delete[] elements;
	elements = temp;
}

template <class T>
void List<T>::free() {
	delete[] elements;
}

template <class T>
void List<T>::copyFrom(const List& other) {
	elements = new T[other.length];
	for (int i = 0; i < other.count; i++)
		elements[i] = other.elements[i];
	length = other.length;
	count = other.count;
}

/* Public */

template <class T>
List<T>::List(const T* elements, unsigned elementsCount) : List() {
	for (unsigned i = 0; i < elementsCount; i++)
		add(elements[i]);
}

template <class T>
void List<T>::add(const T& element) {
	if (length == count) resize();

	elements[count++] = element;
}

template <class T>
bool List<T>::removeAt(unsigned index) {
	if (index >= count) return false;

	delete elements[index];
	for (int i = index; i < count; i++)
		elements[i] = elements[i + 1];
	elements[count--] = nullptr;
}

template <class T>
T& List<T>::operator[](unsigned index) {
	return elements[index];
}

template <class T>
const T& List<T>::operator[](unsigned index) const {
	return elements[index];
}

template <class T>
unsigned List<T>::get_length() const {
	return length;
}

template <class T>
unsigned List<T>::get_count() const {
	return count;
}

// Rule of 4

template <class T>
List<T>::List() {
	length = 8;
	count = 0;
	elements = new T[length];
}

template <class T>
List<T>& List<T>::operator=(const List& other) {
	if (this != &other) {
		free();
		copyFrom(other);
	}
	return *this;
}

template <class T>
List<T>::List(const List& other) {
	copyFrom(other);
}

template <class T>
List<T>::~List() {
	free();
}

// Move semantics

template <class T>
List<T>::List(List&& other) {
	length = other.length;
	count = other.count;
	elements = other.elements;
	other.elements = nullptr;
}

template <class T>
List<T>& List<T>::operator=(List&& other) {
	if (this != &other) {
		free();
		length = other.length;
		count = other.count;
		elements = other.elements;
		other.elements = nullptr;
	}
	return *this;
}