vector.h
2.84 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#ifndef __VECTOR_H__
#define __VECTOR_H__
#include <limits>
template <class C> class vector {
C *data;
unsigned int size;
unsigned int cap;
private:
static unsigned int round_up_to_power_of_2(unsigned w) {
const auto bits = std::numeric_limits<unsigned>::digits;
--w;
for (unsigned s = 1; s < bits; s *= 2)
w |= w >> s;
return ++w;
};
public:
class index_out_of_range {};
explicit vector(unsigned s) {
cap = round_up_to_power_of_2(s);
data = static_cast<C *>(malloc(cap * sizeof(C)));
if (!data)
throw bad_alloc();
size = s;
unsigned i;
try {
for (i = 0; i < size; i++)
new (data + i) C();
} catch (...) {
for (unsigned j = 0; j < i; ++j)
(data + j)->~C();
free(data);
throw;
}
}
~vector() {
for (unsigned j = 0; j < size; ++j)
(data + j)->~C();
free(data);
}
C &operator[](unsigned int pos) {
if (pos >= size)
throw index_out_of_range();
return data[pos];
}
C operator[](unsigned int pos) const {
if (pos >= size)
throw index_out_of_range();
return data[pos];
}
vector(const vector<C> &s) {
cap = s.cap;
data = static_cast<C *>(malloc(cap * sizeof(C)));
if (!data)
throw bad_alloc();
size = s.size;
unsigned i;
try {
for (i = 0; i < size; i++)
new (data + i) C(s.data[i]);
} catch (...) {
for (unsigned j = 0; j < i; ++j)
(data + j)->~C();
free(data);
throw;
}
}
void swap(vector<C> &s) {
C *t1 = s.data;
unsigned int t2 = s.size;
unsigned int t3 = s.cap;
s.data = data;
s.size = size;
data = t1;
size = t2;
cap = t3;
}
vector<C> &operator=(const vector<C> &s) {
if (this == &s)
return *this;
vector<C> n(s);
swap(n);
return *this;
}
friend ostream &operator<<(ostream &o, const vector<C> &v) {
o << '[';
for (unsigned i = 0; i < v.size; i++) {
o << v[i];
if (i != v.size - 1)
o << ',';
};
o << ']';
return o;
}
void push_back(const C &s) {
if (size < cap) {
new (data + size) C(s);
++size;
} else {
if (cap > std::numeric_limits<decltype(size)>::max() / 2)
throw bad_alloc();
unsigned int newcap = (cap == 0) ? 1 : 2 * cap;
C *newdata = static_cast<C *>(malloc(newcap * sizeof(C)));
if (!newdata)
throw bad_alloc();
unsigned i;
try {
for (i = 0; i < size; i++)
new (newdata + i) C(data[i]);
} catch (...) {
for (unsigned j = 0; j < i; ++j)
(newdata + j)->~C();
free(newdata);
throw;
}
new (newdata + size) C(s);
for (unsigned j = 0; j < size; ++j)
(data + j)->~C();
free(data);
++size;
data = newdata;
cap = newcap;
}
}
};
#endif /* __VECTOR_H__ */