-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpandableArrayList.hpp
More file actions
114 lines (106 loc) · 2.76 KB
/
Copy pathExpandableArrayList.hpp
File metadata and controls
114 lines (106 loc) · 2.76 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
102
103
104
105
106
107
108
109
110
111
112
113
114
#pragma once
#include <iostream>
#include <stdexcept>
template <typename Object>
class ExpandableArrayList {
private:
// 指向动态分配数组的指针
int capacity; // 数组的容量
int count; // 数组中元素的实际数量
Object* array;
public:
//公共接口
//E& operator[](int i);
//void resizeList();
//void Clear();
ExpandableArrayList(int initialCapacity = 10) : capacity(initialCapacity), count(0) {
array = new Object[capacity];
}
ExpandableArrayList(int initialCapacity,int initialCount) : capacity(initialCapacity), count(initialCount) {
array = new Object[capacity];
}
~ExpandableArrayList() {
delete[] array;
}
ExpandableArrayList& operator=(const ExpandableArrayList& other)
{
if (array != nullptr)
{
delete[]array;
array = nullptr;
}
count = other.count;
capacity = other.capacity;
array = new Object[capacity];
for (int i = 0; i < count; i++)
{
array[i] = other.array[i];
}
return *this;
}
ExpandableArrayList& operator=(ExpandableArrayList&& other)
{
count = other.count;
capacity = other.capacity;
other.capacity = 0;
other.count = 0;
if (array != nullptr)
{
delete[]array;
array = nullptr;
}
array = other.array;
other.array = nullptr;
return *this;
}
Object& operator[](int i) {
if (i < 0 || i >= count) {
throw std::out_of_range("Index out of range");
}
return array[i];
}
Object& operator[](int i) const {
if (i < 0 || i >= count) {
throw std::out_of_range("Index out of range");
}
return array[i];
}
void resize(int count) {
while (count > this->capacity)resizeList();
this->count = count;
}
void resizeList() {
int newCapacity = capacity * 2;
Object* newArray = new Object[newCapacity];
for (int i = 0; i < count; ++i) {
newArray[i] = array[i];
}
delete[] array;
array = newArray;
capacity = newCapacity;
}
void resizeList(int newCapacity) {
Object* newArray = new Object[newCapacity];
for (int i = 0; i < count; ++i) {
newArray[i] = array[i];
}
delete[] array;
array = newArray;
capacity = newCapacity;
}
void Clear() {
count = 0;
}
void add(const Object& element) {
if (count == capacity) {
resizeList();
}
array[count++] = element;
}
int size() const {
return count;
}
int getCapacity() const {
return capacity;
}
};