-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicArray.cpp
More file actions
100 lines (72 loc) · 1.9 KB
/
Copy pathDynamicArray.cpp
File metadata and controls
100 lines (72 loc) · 1.9 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
#include <iostream>
using namespace std;
template<typename Type>
class DynamicArray{
private:
Type* p;
size_t count;
size_t cap;
void double_capacity(){
Type* new_p = new Type[cap*=2];
for(size_t i=0; i<count; ++i) new_p[i] = p[i];
std::swap(new_p, p);
delete new_p;
}
public:
DynamicArray() : count(0), cap(8), p(new Type[10]){}
void display() const {
cout << "[ ";
for(size_t i=0; i<count; ++i) cout << p[i] << " ";
cout << "]";
}
void push_back(const Type& new_value){
if(count == cap) double_capacity();
p[count++] = new_value;
}
void push_front(const Type& new_value){
insert(new_value);
}
bool insert(const Type& new_value, const size_t& index = 0){
if(index<0 || index>count) return false;
if(count == cap) double_capacity();
for(size_t i=count; i>=index+1; --i) p[i] = p[i-1];
p[index] = new_value;
++count;
return true;
}
bool pop_back(){
if(count==0) return false;
return count--;
}
bool pop_front(){
return remove(0);
}
bool remove(const size_t& index){
if(index<0 || index>=count) return false;
if(count<2) return pop_back();
for(size_t i=index; i<count; ++i) p[i] = p[i+1];
--count;
return true;
}
Type& operator[](const size_t& index){
return p[index];
}
Type operator[](const size_t& index) const {
return p[index];
}
size_t capacity() const {
return cap;
}
size_t size() const {
return count;
}
bool is_empty() const {
return count==0;
}
void clear(){
count = 0;
}
~DynamicArray(){
delete[] p;
}
};