-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.cpp
78 lines (63 loc) · 1.26 KB
/
vector.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
#include <iostream>
#include <cassert>
using namespace std;
template <typename T>
class Vect {
private:
size_t mysize;
size_t mycapacity;
T* mydata;
public:
Vect() {
mydata = nullptr;
mysize = 0;
mycapacity = 0;
}
Vect(size_t InitialCapacity) {
mydata = new T[InitialCapacity];
mysize = 0;
mycapacity = InitialCapacity;
}
~Vect() {
delete[] mydata;
}
int size() {
return mysize;
}
int capacity() {
return mycapacity;
}
int operator[](size_t index){
if (index < 0 || index >= mysize) {
return -1;
}
return mydata[index];
}
bool empty() {
return mysize == 0;
}
void push_back(T value) {
if (mysize == mycapacity) {
mycapacity = mycapacity == 0 ? 1 : mycapacity * 2;
T* newdata = new T[mycapacity];
for (int i = 0; i < mysize; i++) {
newdata[i] = mydata[i];
}
delete[] mydata; // Deallocate old data
mydata = newdata;
}
mydata[mysize] = value;
mysize++;
}
};
int main() {
Vect<int> nums;
for (int i = 0; i < 10; i++) {
nums.push_back(i);
}
std::cout << nums.size() << std::endl;
for (int i = 0; i < 10; i++) {
std::cout << nums[i] << std::endl;
}
return 0;
}