- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 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
template<class T>
struct GrowArray
{
T *mem = nullptr;
size_t count = 0;
size_t alloc = 0;
GrowArray(size_t init = 0)
{
if(init)
Grow(init);
}
~GrowArray()
{
if(mem)
free(mem);
mem = nullptr;
count = 0;
alloc = 0;
}
// non-copyable
GrowArray(const GrowArray &) = delete;
GrowArray &operator = (const GrowArray &) = delete;
void noinline Grow(size_t size)
{
if(!size)
size = 32;
T *newMem = (T*)(mem? realloc(mem, sizeof(T) * size): malloc(sizeof(T)*size));
if(!newMem)
return;
alloc = size;
mem = newMem;
}
// TODO: insert/append
bool Add(const T& newVal)
{
size_t newIdx = count + 1;
if(unlikely(newIdx > alloc))
Grow(alloc * 2);
if(unlikely(newIdx > alloc))
return false;
mem[count] = newVal;
count = newIdx;
return true;
}
// TODO: test
bool RemoveAt(size_t idx)
{
if(idx < count)
memmove(&mem[idx], &mem[idx+1], sizeof(T) * (count - idx - 1));
if(idx <= count)
{
count--;
return true;
}
return false;
}
T& operator[](size_t i) const
{
return mem[i];
}
};
Комментарии (0) RSS
Добавить комментарий