Last active
October 10, 2020 23:17
-
-
Save Phildo/7bdfcd545ad959fe7aad4beb7c892b60 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <initializer_list> | |
template<class T> | |
class DArray | |
{ | |
public: | |
size_t size = 0; | |
size_t length = 0; | |
T *d{}; | |
DArray<T>() {} | |
DArray<T>(std::initializer_list<T> &ini) | |
{ | |
assert(!d); | |
if(!ini.size()) return; | |
prefill(ini.size()); | |
for(size_t i = 0; i < length; i++) | |
d[i] = *(ini.begin()+i); | |
} | |
void expand(size_t nsize) | |
{ | |
assert(nsize); | |
if(nsize <= size) return; | |
size = nsize; | |
if(!d) d = malloc(sizeof(T)*size); | |
else d = realloc(d,sizeof(T)*size); | |
} | |
void prefill(size_t nsize) | |
{ | |
assert(nsize > length); | |
if(nsize < size) expand(nsize); | |
length = nsize; | |
} | |
T& append(T &v) | |
{ | |
assert(d); | |
if(length == size) | |
{ | |
size *= 2; | |
d = realloc(v,sizeof(T)*size); | |
} | |
d[length++] = v; | |
} | |
void remove(size_t i) | |
{ | |
assert(i < length); | |
for(size_t j = i; j < length-1; j++) | |
d[j] = j+1; | |
length--; | |
} | |
DArray<T>& operator=(std::initializer_list<T> &ini) | |
{ | |
assert(!d); | |
if(!ini.size()) return; | |
prefill(ini.size()); | |
for(size_t i = 0; i < length; i++) | |
d[i] = *(ini.begin()+i); | |
} | |
T& operator[](size_t i) { | |
assert(i < length); | |
return d[i]; | |
}; | |
void cleanup() | |
{ | |
if(d) free(d); | |
d = 0; | |
size = 0; | |
length = 0; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment