-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.cpp
94 lines (93 loc) · 2.02 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class Vector {
private :
int size;
int capacity;
T* array;
void expand(int newCapacity) {
if (newCapacity <= capacity) {
return;
}
T* old = array;
array = new T[newCapacity];
for (int i = 0; i < capacity; i++) {
array[i] = old[i];
}
delete[]old;
capacity = newCapacity;
}
public:
Vector(int initCapacity = 100) {
size = 0;
capacity = initCapacity;
array = new T[capacity];
}
~Vector() {
delete[]array;
}
Vector& operator=(T* obj) {
if (this != obj) {
delete[]array;
size = obj.size;
capacity = obj.capacity;
array = new T[capacity];
for (int i = 0; i < capacity; i++) {
array[i] = obj.array[i];
}
}
return *this;
}
int Size() {
return size;
}
bool empty() {
return (size==0);
}
T &operator[](int i) {
return array[i];
}
void push_back(T newElement) {
if (size==capacity) {
expand(2*size);
}
array[size] = newElement;
size++;
}
void pop_back() {
size--;
}
void insert(int position, T newElement) {
if (size == capacity) {
expand(2 * size);
}
for (int i = size; i > position; i--) {
array[i] = array[i - 1];
}
array[position] = newElement;
size++;
}
void erase(int position) {
for (int i = position; i < size;i++) {
array[i] = array[i + 1];
}
size--;
}
void clean() {
size = 0;
}
};
int main()
{
Vector<int>a;
for (int i = 0; i < 5; i++) {
cout << "vui long nhap vao cac phan tu thu " <<i+1<< " cua mang" << endl;
int temp;
cin >> temp;
a.push_back(temp);
cout << a.Size()<<endl;
}
cout << a[3];
}