#include <stdio.h>
// Аллокатор
template<typename T>
struct myAlloc {
static T* get_alloc(size_t n) {
T* p;
try {
p = new T[n];
} catch(...) {
return NULL;
}
return p;
}
static void dispose(T*& p) {
if(p != NULL)
delete[] p;
p = NULL;
}
// память выделяется блоками, можешь указать оптимальный собственный размер
static size_t get_block(void) {
return 32u;
}
};
// динамический массив
template<typename T, typename Alloc = myAlloc<T> >
class myArray {
private:
T* p;
size_t n;
size_t m;
public:
myArray(void) : p(NULL), n(0u), m(Alloc::get_block()){}
explicit myArray(const myArray& o)
: p(NULL), n(0u), m(Alloc::get_block()) {
this->Copy(o);
}
~myArray() {
this->Clear();
}
// добавление
void Add(const T& v) {
if(p == NULL) {
if((p = Alloc::get_alloc(m)) == NULL)
return;
}
if(n >= m) {
m += Alloc::get_block();
T* t = Alloc::get_alloc(m);
if(t == NULL)
return;
for(size_t i = 0u; i < n; i++)
t[i] = p[i];
Alloc::dispose(p);
p = t;
}
p[n++] = v;
}
// копирование
void Copy(const myArray& o) {
if(o.Empty())
return;
if(o.GetSize() > n) {
this->Clear();
if((p = Alloc::get_alloc(o.GetSize())) == NULL)
return;
}
for(size_t i = 0u; i < o.GetSize(); i++)
p[i] = o[i];
n = o.GetSize();
}
// удаление отрезка с first до last позиции за O(n)
void Delete(size_t f, size_t l) {
if((p == NULL) || (! n) || (l > n))
return;
size_t c = l - f;
for(size_t k = f; k < (n - c); k++)
p[k] = p[k + c];
n -= c;
}
inline T& operator [] (size_t i) {
return p[i];
}
inline T& operator [] (size_t i) const {
return p[i];
}
myArray& operator = (const myArray& o) {
this->Copy(o);
return *this;
}
// размер
size_t GetSize(void) const {
return n;
}
bool Empty(void) const {
return ((p == NULL) || (! n));
}
// удаление массива из памяти
void Clear(void) {
if(p != NULL)
Alloc::dispose(p);
n = 0;
m = Alloc::get_block();
}
};
int main(void) {
myArray<int> arr;
for(int j = 1; j < 30; j++)
arr.Add(j);
// удалить элементы с 10-ой по 20-ой позиции
arr.Delete(9, 20);
// вывести 1-ый и 2-ой элемент
printf("first = %d\tlast = %d\n",
arr[0], arr[arr.GetSize() - 1]);
myArray<int> b(arr);
for(size_t i = 0u; i < b.GetSize(); i++)
printf("%d\n", b[i]);
b.Clear();
arr.Clear();
return 0;
}