Repository navigation
Expand file tree
/
Copy pathCustomVector.cpp
More file actions
101 lines (88 loc) · 1.89 KB
/
Copy pathCustomVector.cpp
File metadata and controls
101 lines (88 loc) · 1.89 KB
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
#include<iostream>
#include<utility>
#include<stdexcept>
template <typename T>
class CustomVector {
private:
T* _data;
size_t _capacity;
size_t _size;
void reallocate(size_t newCapacity)
{
T* newData = new T[newCapacity];
for (size_t i = 0;i < _size;++ i)
{
newData[i] = std::move(_data[i]);
}
delete[] _data;
_capacity = newCapacity;
_data = newData;
}
public:
CustomVector(size_t capacity = 1) : _capacity(capacity), _size(0), _data(new T[capacity])
{
}
~CustomVector()
{
delete[] _data;
}
T& operator[](size_t index)
{
if (index >= _size) {
throw std::out_of_range("Index out of range");
}
return _data[index];
}
CustomVector<T>& operator=(const CustomVector<T>& other)
{
if(this != &other)
{
delete[] _data;
_capacity = other._capacity;
_size = other._size;
_data = new T[_capacity];
for(size_t i = 0;i < _size;++ i)
{
_data[i] = other._data[i];
}
}
return *this;
}
void push_back(const T& data)
{
if(_size == _capacity)
{
if(_capacity == 0) reallocate(1);
else reallocate(_capacity * 2);
}
_data[_size] = data;
_size ++;
}
void pop_back()
{
if(_size > 0)
{
_size --;
}
}
size_t size() const
{
return _size;
}
size_t capacity() const
{
return _capacity;
}
bool empty() const
{
return _size == 0;
}
};
int main() {
CustomVector<int> test;
test.push_back(1);
test.push_back(2);
test.push_back(3);
for(int i = 0;i < test.size();++ i) std::cout<<test[i]<<'\n';
return 0;
}