Website Summary Files Commits Branches @commit @diff @stats
path: root / pract KN / week8 / Vector.cpp
blob: b288e12e4a85d4c20b6325642b8a1afbc60d8e58 (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
#include "Vector.h"

void Vector::resize()
{
	capacity *= 2;
	int* newArr = new int[capacity];
	for (size_t i = 0; i < size; i++)
	{
		newArr[i] = arr[i];
	}
	free();
	arr = newArr;
}

void Vector::free()
{
	delete[] arr;
}

void Vector::copyFrom(const Vector& other)
{
	size = other.size;
	capacity = other.capacity;
	arr = new int[capacity];
	for (int i = 0; i < size; i++)
	{
		arr[i] = other.arr[i];
	}
}

Vector::Vector()
{
	arr = new int[2];
	capacity = 2;
	size = 0;
}

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

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

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

void Vector::push_back(const int element)
{
	if (size < capacity) {
		arr[size] = element;
		size++;
	}
	else
	{
		resize();
		push_back(element);
	}
}

int Vector::getSize() const
{
	return size;
}

int& Vector::operator[](const int index)
{
	if (index >= 0 && index < size) {
		return arr[index];
	}
	throw std::exception("Out of range exception");

}

const int& Vector::operator[](int index) const
{
	if (index >= 0 && index < size) {
		return arr[index];
	}
	throw std::exception("Out of range exception");
}