-
Notifications
You must be signed in to change notification settings - Fork 2
/
Dynamic array implementation.cpp
158 lines (126 loc) · 2.96 KB
/
Dynamic array implementation.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
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
149
150
151
152
153
154
155
156
157
158
// Dynamic array implementation
// in other words Simplified version of vector class
// array's size must be changed manually
#include <iostream>
using namespace std;
template <typename T>
class Vector
{
private:
int capacity;
// int elementCount;
T* data;
public:
//Constructors
//Default
Vector(){
capacity = 0;
data = NULL;
}
explicit Vector(int sz){
data = new T[sz];
capacity = sz;
}
Vector(int sz, const T& cont){
data = new T[sz];
capacity = sz;
for(int i= 0; i<sz; i++){
data[i] = cont;
}
}
Vector(T& cpy){
if(cpy.capacity > capacity){
clear();
data = new T[cpy.capacity];
}
capacity = cpy.capacity;
for(int i= 0; i<capacity; i++){
data[i] = cpy.data[i];
}
}
//TODO copy constructor
Vector(const Vector& cpy){
if(this == &cpy) return;
clear();
resize(cpy.capacity); //TODO check for bugs
for(int i= 0; i<cpy.capacity; i++){
data[i] = cpy.data[i];
}
}
//Destructor
~Vector(){
delete[] data;
}
void resize(int newSize){
T* temp= new T[newSize];
if(newSize < capacity) capacity = newSize;
for(int i= 0; i<capacity; i++){
temp[i] = data[i];
}
capacity = newSize;
swap(data, temp);
delete[] temp;
}
void clear(){
delete[] data;
capacity = 0;
data= NULL;
}
int size(){
return capacity;
}
void insert(int index, const T& cpy){
if(index<0 || index>capacity-1){
std::cerr<< "Can not remove! Invalid index\n";
return;
}
for(int i= capacity-1; i>index; i--){
data[i] = data[i-1];
}
data[index]= cpy;
}
void remove(const int index){
if(index<0 || index>capacity-1){
std::cerr<< "Can not remove! Invalid index\n";
return;
}
for(int i= index; i<capacity-1; i++){
data[i] = data[i+1];
}
}
T& operator[](int index){
return data[index];
}
void operator=(Vector& cpy){
if(cpy.capacity > capacity){
clear();
data = new T[cpy.capacity];
}
capacity = cpy.capacity;
for(int i= 0; i<capacity; i++){
data[i] = cpy.data[i];
}
}
//print whole array
void print(){
for(int i= 0; i<capacity; i++){
cout<< data[i] <<" ";
}
cout<<endl;
}
};
int main(void)
{
Vector<int> a(5);
a[0]= 1;
a[1]= 2;
a[2]= 3;
a[3]= 4;
a.remove(1);
a.remove(0);
a.insert(0, 3);
a.insert(2, 8);
a.insert(3, 5);
a.print();
return 0;
}