-
Notifications
You must be signed in to change notification settings - Fork 67
/
VariableSizeVector.h
110 lines (94 loc) · 2.12 KB
/
VariableSizeVector.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
#pragma once
//
// A variable-size vector that does not perform any memory allocation except to grow.
//
template<typename V, int grow = 150, bool big = false>
class VariableSizeVector
{
private:
inline static void* allocate(size_t bytes)
{
return big ? BigAlloc(bytes) : malloc(bytes);
}
inline static void deallocate(void* p)
{
if (big) { BigDealloc(p); } else { free(p); }
}
public:
VariableSizeVector(int i_capacity = 16)
: entries(NULL), count(0), capacity(i_capacity)
{
}
~VariableSizeVector()
{
if (entries != NULL) {
deallocate(entries);
entries = NULL;
count = 0;
}
}
void operator=(VariableSizeVector<V>& other)
{
entries = other.entries;
capacity = other.capacity;
count = other.count;
other.entries = NULL;
other.count = 0;
}
void reserve(int capacity)
{
V* old = entries;
this->capacity = capacity;
entries = (V*) allocate(capacity * sizeof(V));
if (old != NULL) {
memcpy(entries, old, count * sizeof(V));
deallocate(old);
}
}
inline void clear()
{
count = 0;
}
inline int size()
{
return count;
}
inline void push_back(V& value)
{
if (entries == NULL) {
reserve(capacity);
} else if (count == capacity) {
reserve((int) (((_int64) count * grow) / 100));
}
_ASSERT(count < capacity);
entries[count++] = value;
}
inline bool add(const V& value)
{
for (int i = 0; i < count; i++) {
if (entries[i] == value) {
return false;
}
}
push_back(value);
return true;
}
inline V& operator[](int index)
{
_ASSERT(index >= 0 && index < count);
return entries[index];
}
typedef V* iterator;
iterator begin()
{
return entries;
}
iterator end()
{
return &entries[count];
}
private:
V *entries;
int capacity;
int count;
};