blob: 5388aab04a64d53db704a081a470d49916f48a46 (
plain)
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
|
#ifndef COOLARRAY_H_
#define COOLARRAY_H_
#include <memory>
#include <initializer_list>
template<class T>
class CoolArray {
private:
T *buffer;
size_t _size, _capacity;
public:
CoolArray(void) {
buffer = nullptr;
_size = 0;
_capacity = 0;
}
CoolArray(size_t n, const T& value=0) {
buffer = new T[n];
_size = n;
_capacity = n;
std::fill(buffer, buffer + _size, value);
}
~CoolArray(void) {
delete[] buffer;
}
T& operator[](size_t idx) {
return buffer[idx];
}
void operator=(std::initializer_list<T> a) {
if (buffer != nullptr)
delete[] buffer;
_size = a.size();
buffer = new T[_size];
_capacity = _size;
std::copy(a.begin(), a.end(), buffer);
}
template<class Func>
void remove_if(Func f) {
for (size_t i = 0; i < _size; ++i) {
if (f(buffer[i]))
std::move(buffer + i + 1, buffer + _size--, buffer + i);
}
}
void reserve(size_t n) {
if (buffer != nullptr) {
T *newbuf = new T[n];
std::copy(buffer, buffer + (_size < n ? _size : n), newbuf);
_capacity = n;
delete[] buffer;
buffer = newbuf;
} else {
buffer = new T[n];
_capacity = n;
}
}
void resize(size_t n) {
reserve(n);
_size = n;
}
void clear(void) {
delete[] buffer;
_size = 0;
_capacity = 0;
}
size_t size(void) const {
return _size;
}
size_t capacity(void) const {
return _capacity;
}
T& front(void) {
return buffer[0];
}
T& back(void) {
return buffer[_size - 1];
}
T* begin(void) {
return buffer;
}
T* end(void) {
return buffer + _size;
}
void push_back(const T& x) {
if (_size >= _capacity)
reserve(_capacity + 5);
buffer[_size++] = x;
}
void pop_back(void) {
--_size;
}
};
#endif // COOLARRAY_H_
|