-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom_array.cpp
executable file
·138 lines (120 loc) · 2.28 KB
/
custom_array.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
#include <iostream>
#include <stdexcept>
#include <cstring>
template <typename T>
class custom_array
{
T *list;
int size;
int capacity;
public:
custom_array();
~custom_array();
int get_size();
void push_back(T);
T pop_back();
T at(int);
bool is_full();
void resize(int n = 0);
int get_capacity();
void print_list();
};
template <typename T>
custom_array<T>::custom_array()
{
this->size = 0;
this->capacity = 5;
this->list = new T[this->capacity];
}
template <typename T>
custom_array<T>::~custom_array()
{
delete[] this->list;
}
template <typename T>
T custom_array<T>::at(int idx)
{
if (idx < size)
{
return this->list[idx];
}
else
{
throw std::out_of_range("List index out of Range");
}
}
template <typename T>
int custom_array<T>::get_size()
{
return this->size;
}
template <typename T>
void custom_array<T>::push_back(T data)
{
if (is_full())
{
resize();
}
this->list[this->size] = data;
size++;
}
template <typename T>
int custom_array<T>::get_capacity()
{
return this->capacity;
}
template <typename T>
T custom_array<T>::pop_back()
{
if (size == 0)
{
throw std::out_of_range("List is empty");
}
T popval = this->list[size - 1];
size--;
return popval;
}
template <typename T>
bool custom_array<T>::is_full()
{
return size == capacity;
}
template <typename T>
void custom_array<T>::resize(int n)
{
int newCapacity;
if (n)
{
newCapacity = n;
}
else
{
newCapacity = capacity * 2;
}
T *newList = new T[newCapacity];
std::memcpy(newList, list, size * sizeof(T));
delete[] list;
list = newList;
capacity = newCapacity;
}
template <typename T>
void custom_array<T>::print_list()
{
for (int i = 0; i < this->size; i++)
{
std::cout << this->list[i] << " ";
}
std::cout << std::endl;
}
int main()
{
custom_array<int> list;
for (int i = 100; i < 1200; i += 100)
{
list.push_back(i);
}
list.print_list();
list.resize(40);
std::cout << list.get_capacity() << std::endl;
return 0;
}