Skip to content

Commit cd7f9fc

Browse files
authored
vector模拟实现
1 parent 0b58dc0 commit cd7f9fc

File tree

1 file changed

+152
-0
lines changed

1 file changed

+152
-0
lines changed

vector

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
#include<iostream>
2+
#include<string.h>
3+
#include<assert.h>
4+
using namespace std;
5+
6+
namespace myvector
7+
{
8+
template<class T>
9+
class vector
10+
{
11+
public:
12+
typedef T* iterator;
13+
14+
iterator begin()
15+
{
16+
return start;
17+
}
18+
19+
iterator end()
20+
{
21+
return finish;
22+
}
23+
24+
//默认构造函数
25+
vector()
26+
:start(nullptr)
27+
, finish(nullptr)
28+
, end_of_storage(nullptr)
29+
{}
30+
//容量
31+
size_t capacity()
32+
{
33+
return end_of_storage - start;
34+
}
35+
36+
size_t size()
37+
{
38+
return finish - start;
39+
}
40+
41+
void reserve(size_t n)
42+
{
43+
if (n > capacity())
44+
{
45+
//开新空间
46+
T* tmp = new T[n];
47+
//拷贝旧空间的内容
48+
memcpy(tmp, start, sizeof(T)*size());
49+
//改变容量
50+
finish = tmp + size();
51+
end_of_storage = tmp + n;
52+
//释放旧空间
53+
T* tmp1 = start;
54+
start = tmp;
55+
tmp = nullptr;
56+
}
57+
}
58+
59+
void resize(size_t n, const T& val = T())
60+
{
61+
//判断容量
62+
if (n > capacity())
63+
reserve(n);
64+
//如果n<size
65+
if (n < size())
66+
{
67+
finish = start + n;
68+
}
69+
else
70+
{
71+
while (finish != start + n)
72+
{
73+
*finish = val;
74+
finish++;
75+
}
76+
}
77+
}
78+
//检查空间
79+
void check_capacity()
80+
{
81+
if (finish == end_of_storage)
82+
{
83+
//如果当前不为空,就扩2倍,为空就开4个吧
84+
size_t newcapacity = finish == nullptr ? 4 : capacity()*2;
85+
reserve(newcapacity);
86+
}
87+
}
88+
89+
T& operator[](size_t pos)
90+
{
91+
assert(pos < size());
92+
return start[pos];
93+
}
94+
95+
//插入
96+
void push_back(const T& x)
97+
{
98+
insert(finish,x);
99+
}
100+
101+
iterator insert(iterator pos, const T& x)
102+
{
103+
assert(pos >= start && pos <= finish);
104+
size_t pos1 = pos - start;
105+
check_capacity();
106+
//解决迭代器失效
107+
pos = start + pos1;
108+
//移动数据
109+
iterator end = finish;
110+
while (end >= pos)
111+
{
112+
*(end + 1) = *end;
113+
end--;
114+
}
115+
//插入数据
116+
*pos = x;
117+
finish++;
118+
return pos;
119+
}
120+
121+
//删除数据
122+
void pop_back()
123+
{
124+
assert(finish > start);
125+
finish--;
126+
}
127+
iterator erase(iterator pos)
128+
{
129+
assert(pos >= start && pos < finish);
130+
131+
iterator it = pos + 1;
132+
while (it != finish)
133+
{
134+
*(it - 1) = *it;
135+
++it;
136+
}
137+
--finish;
138+
139+
return pos;
140+
}
141+
//析构函数
142+
~vector()
143+
{
144+
delete[] start;
145+
start = finish = end_of_storage = nullptr;
146+
}
147+
private:
148+
iterator start;
149+
iterator finish;
150+
iterator end_of_storage;
151+
};
152+
}

0 commit comments

Comments
 (0)