-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyVector.h
More file actions
82 lines (66 loc) · 1.64 KB
/
myVector.h
File metadata and controls
82 lines (66 loc) · 1.64 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
#ifndef __MYVECTOR_H__
#define __MYVECTOR_H__
#include <memory>
using namespace std;
template<class T>
class myVector {
private:
T *start, *end, *storageEnd;
allocator<T> alloc;
void reallocate() {
size_t oldSize = end - start;
size_t newSize = 2 * oldSize;
if (newSize == 0)
newSize = 1;
auto newSpace = alloc.allocate(newSize);
uninitialized_copy(start, end, newSpace);
for (auto i = start; i != end; i++) {
alloc.destroy(i);
}
if (start != NULL)
alloc.deallocate(start, oldSize);
start = newSpace;
end = newSpace + oldSize;
storageEnd = newSpace + newSize;
}
public:
typedef T value_type;
typedef T *iterator;
typedef T &reference;
// typedef T* pointer;
myVector() : start(NULL), end(NULL), storageEnd(NULL) {
}
void push_back(const value_type target) {
if (end == storageEnd) {
reallocate();
}
alloc.construct(end, target);
end++;
}
const iterator erase(iterator target) {
copy(target + 1, end, target);
alloc.destroy(end);
end--;
return target - 1;
}
const iterator Start() {
return start;
}
const iterator End() {
return end - 1;
}
int Size() {
return end - start;
}
reference operator[](const size_t n) {
return *(start + n);
}
void destroy() {
for (iterator i = start; i != end; i++) {
alloc.destroy(i);
}
if (start != NULL)
alloc.deallocate(start, storageEnd - start);
}
};
#endif