-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyvector.cpp
124 lines (120 loc) · 2.05 KB
/
Myvector.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
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<assert.h>
#include<string>
//模拟实现vector
template<class T>
class Myvector
{
typedef T* Iterator;
typedef const T* ConstIterator;
private:
Iterator _start;
Iterator _finish;
Iterator _endofstorage;
public:
Myvector() //构造
:_start(NULL)
, _finish(NULL)
, _endofstorage(NULL)
{
cout << "~Myvector()" << endl;
}
Myvector(const Myvector<T>& v) //拷贝构造,考size还是考capacity? 为了结社空间是拷贝size
{
_start = new T[v.Size()];
for (size_t i = 0; i < v.Size(); i++)
{
_start[i] = v[i];
}
_finish = _start + v.Size();
_endofstorage = _finish;
}
Myvector<T>& operator=(const Myvector<T>& v)
{
if (this != &v)
{
if (this->Size()) //原来的空间存在
Destory();
_start = new T[v.Size()];
for (size_t i = 0; i < v.Size(); i++) //拷贝
{
_start[i] = v[i];
}
_finish = _start + v.Size();
_endofstorage = _start + v.Capacity();
}
return *this;
}
//增容
void CheckCapacity()
{
if (Size() >= Capacity())
Capacity() = Capacity() + Capacity() / 2; //为什么需要1.5倍增容
Expand(Capacity());
}
//增加固定的体积然后拷贝数据函数
void Expand(size_t n)
{
if (n == 0)
return;
T* tmp = new T[n];
assert(tmp);
for (size_t i = 0; i < Size(); i++)
{
tmp[i] = _start[i];
}
delete[] _start;
_start = tmp;
_finish = _start + Size();
_endofstorage = _start + n;
}
void PushBack(const T& data) //尾插
{
CheckCapacity();
*_finish = data;
_finish++;
}
void PopBack() //尾删
{
if (Size() <= 0)
return;
_finish--;
}
void ReSize(size_t n)
{
}
void Reserve(size_t n) //Reserve的值可以比原来小?
{
if (n <= Size())
return;
Expand(n);
}
T& operator[]()
{
return _start[i];
}
size_t Size()
{
return _finish - _start;
}
size_t Capacity()
{
return _endofstorage - _start;
}
void Destory()
{
delete[]_start;
_start = NULL;
_finish = NULL;
_endofstorage = NULL;
}
};
void test()
{
}
int main()
{
test();
return 0;
}