blob: 073d12da3a0bb5972a4770b23cf06302cccda69b (
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
|
#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];
}
}
void Vector::swap(const int ind1, const int ind2) {
int temp = arr[ind1];
arr[ind1] = arr[ind2];
arr[ind2] = temp;
}
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 "Out of range exception";
}
const int& Vector::operator[](int index) const
{
if (index >= 0 && index < size) {
return arr[index];
}
throw "Out of range exception";
}
void Vector::deleteAt(const int index) {
for (int i = index; i < size; i++) {
arr[i] = arr[i + 1];
}
pop_back();
}
void Vector::pop_back() {
arr[size--] = int();
}
int Vector::findItem(const int item) const {
for (int i = 0; i < size; i++) {
if (arr[i] == item)
return i;
}
return -1;
}
void Vector::clear() {
delete[] arr;
size = capacity = 0;
}
void Vector::sort() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (arr[i] > arr[j])
swap(i, j);
}
}
}
void Vector::reverse() {
for (int halfSize = size / 2, offset = 0; offset < halfSize; offset++)
swap(offset, size - offset - 1);
}
std::ostream& operator<<(std::ostream& ostr, const Vector& vec) {
ostr << "<";
for (int i = 0; i < vec.getSize() - 2; i++) {
ostr << vec[i] << ", ";
}
ostr << vec[vec.getSize() - 1] << ">";
return ostr;
}
std::istream& operator<<(std::istream& istr, const Vector& vec) {
return istr;
}
|