-
Notifications
You must be signed in to change notification settings - Fork 16
/
vector.h
174 lines (146 loc) · 3.45 KB
/
vector.h
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#ifndef _SUMMERCAMP_VECTOR_H
#define _SUMMERCAMP_VECTOR_H
#include <vector>
namespace summercamp {
template <typename T>
class vector
{
public:
vector():m_nSize(0), m_pData(nullptr), m_nMax(0){}// 缺省构造函数
vector(int nSize, T dValue):m_nSize(nSize), m_pData(new T[nSize]), m_nMax(nSize){}
~vector(){Free();}
int capacity(){return m_nMax;}
int size(){return m_nSize;}
bool empty(){return m_nSize?0:1;}
bool reserve(int capacity)
{
if(capacity <= m_nMax)
return 1;
else if(capacity > m_nMax)
{
T* newdata = new T[capacity];
for(int i = 0; i < m_nSize; ++i)
{
*(newdata+i) = *(m_pData+i);
}
delete []m_pData;
m_pData = newdata;
newdata = nullptr;
m_nMax = capacity;
return 1;
}
}
bool push_back(T data)
{
if(m_nMax == 0)
{
resize(2);
}
else if(m_nSize == m_nMax)
{
resize(2 * m_nMax);
}
*(m_pData + m_nSize) = data;
m_nSize++;
return 1;
}
bool resize(int nSize)
{
T *newdata = new T[nSize];
if(nSize > m_nSize)
{
for(int i = 0; i < m_nSize; i++)
{
*(newdata+i) = *(m_pData+i);
}
for(int i = m_nSize; i < nSize; i++)
{
*(newdata+i) = (T)0;
}
}
else
{
for(int i = 0; i < nSize; i++)
{
*(newdata+i) = *(m_pData+i);
}
m_nSize = nSize;
}
delete []m_pData;
m_pData = newdata;
newdata = nullptr;
m_nMax = nSize;
return 1;
}
bool resize(int nSize, T data)
{
if(nSize > m_nMax)
{
T *newdata = new T[nSize];
for(int i = 0; i < m_nSize; i++)
{
*(newdata+i) = *(m_pData+i);
}
for(int i = m_nSize; i < nSize; i++)
{
*(newdata+i) = data;
}
delete []m_pData;
m_pData = newdata;
newdata = nullptr;
m_nMax = nSize;
}
else if(nSize >= m_nSize)
{
for(int i = m_nSize; i < nSize; i++)
{
*(m_pData + i) = data;
}
}
else if(nSize < m_nSize)
{
for(int i = nSize; i > m_nSize; --i)
{
delete (m_pData + i);
}
}
m_nSize = nSize;
return 1;
}
T& operator[] (int nIndex) const // 重载[]操作符,以便像传统数组那样通过a[k]来获取元素值
{
if(InvalidateIndex(nIndex))
{
return *(m_pData + nIndex);
}
}
bool clear()
{
m_nSize = 0;
delete []m_pData;
}
private:
T *m_pData;// 存放数组的动态内存指针
int m_nSize;// 数组的元素个数
int m_nMax;//预留给动态数组的内存大小
private:
void Init(); // 初始化
void Free()// 释放动态内存
{
delete []m_pData;
m_pData = nullptr;
}
inline int InvalidateIndex(const int nIndex) const // 判断下标的合法性
{
if(nIndex >= m_nSize)
{
return 0;
}
else
{
return 1;
}
}
};
}
#endif