-
Notifications
You must be signed in to change notification settings - Fork 3
/
DynArray.h
46 lines (38 loc) · 1.34 KB
/
DynArray.h
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
#pragma once
template <class T> class DynArray {
private:
T* pointer;
size_t length;
void freeP() {
if(length)
delete[] pointer;
pointer = nullptr;
length = 0;
}
void setsize(size_t newlen) {
if(newlen)
pointer = new T[newlen];
length = newlen;
}
public:
void resize(size_t newlen) {
freeP();
setsize(newlen);
}
size_t size() const { return length; }
T* data() { return pointer; }
const T* data() const { return pointer; }
T* begin() { return pointer; }
T* end() { return pointer + length; }
const T* begin() const { return pointer; }
const T* end() const { return pointer + length; }
T& operator[] (size_t index) { return pointer[index]; }
const T& operator[] (size_t index) const { return pointer[index]; }
DynArray() { pointer = nullptr; length = 0; }
DynArray(size_t len) { setsize(len); }
DynArray(const DynArray &other) { setsize(other.length); memcpy(pointer, other.pointer, length * sizeof(T)); }
DynArray(DynArray &&other) noexcept { pointer = other.pointer; length = other.length; other.pointer = nullptr; other.length = 0; }
void operator=(const DynArray &other) { resize(other.length); memcpy(pointer, other.pointer, length * sizeof(T)); }
void operator=(DynArray &&other) noexcept { freeP(); pointer = other.pointer; length = other.length; other.pointer = nullptr; other.length = 0; }
~DynArray() { freeP(); }
};