-
Notifications
You must be signed in to change notification settings - Fork 2
/
static_array.h
138 lines (104 loc) · 2.73 KB
/
static_array.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
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
137
138
//
// Static array class.
//
#pragma once
template <typename T, uint max_size>
class static_array {
T data_[max_size];
uint size_;
public:
explicit static_array(int sz = 0) {
resize(sz);
}
static_array(int sz, T val) {
resize(sz);
fill(val);
}
static_array(const static_array<T, max_size> &another) {
resize(another.size_);
for (uint i = 0; i < size_; i++) {
data_[i] = another.data_[i];
}
}
void fill(T val = 0) {
for (uint i = 0; i < size_; i++) {
data_[i] = val;
}
}
const static_array<T, max_size> &operator =(const static_array<T, max_size> &another) {
resize(another.size_);
for (uint i = 0; i < size_; i++) {
data_[i] = another.data_[i];
}
return *this;
}
T *begin() { return data_; }
T *end() { return data_ + size_; }
const T *begin() const { return data_; }
const T *end() const { return data_ + size_; }
T *data() { return data_; }
const T *data() const { return data_; }
uint size() const { return size_; }
bool empty() const { return !size_; }
const T &operator[](uint idx) const {
assert(idx < size_);
return data_[idx];
}
T &operator[](uint idx) {
assert(idx < size_);
return data_[idx];
}
void resize(uint new_size) {
assert(new_size <= max_size);
size_ = new_size;
}
template <uint another_size>
bool operator ==(const static_array<T, another_size> &another) const {
bool res = true;
for (uint i = 0; i < size_; i++) {
res &= data_[i] == another.data_[i];
}
return res;
}
bool all_equal_to(T val) const {
bool res = true;
for (uint i = 0; i < size_; i++) {
res &= data_[i] == val;
}
return res;
}
uint count(T val) const {
uint res = 0;
for (uint i = 0; i < size_; i++) {
res += data_[i] == val;
}
return res;
}
uint count(const std::function<bool(T)> &lambda) const {
uint res = 0;
for (uint i = 0; i < size_; i++) {
res += lambda(data_[i]);
}
return res;
}
template <uint another_size>
bool operator !=(const static_array<T, another_size> &another) const {
return !(*this == another);
}
void push_back(T val) {
uint sz = size();
resize(sz + 1);
data_[sz] = val;
}
T pop_back() {
T res = back();
resize(size() - 1);
return res;
}
T front() const {
return (*this)[0];
}
T back() const {
return (*this)[size_ - 1];
}
};