For our school project we have to use arrays extensively, so I decided to create a pretty simple to use wrapper class. However since I created this class, the RAM usage of my arduino raised quite a bit. From a couple of bytes, to almost half a kilobyte. Maybe someone can give me a hint to make the class below use less RAM?
#ifndef Array_h
#define Array_h
template<class T>
class Array {
public:
Array()
{
//Initialize array
values = new T[0];
}
~Array()
{
//Garbage cleaning
delete [] values;
};
//Return the size of the array
int size()
{
return numItems;
};
//Add item
void add(T item)
{
//Create an array of the current size + 1
T* tmp = new T[size()+1];
//Add items to new array
for(int i = 0; i < size(); i++)
{
tmp[i] = values[i];
}
//Add the new item
tmp[size()] = item;
//Set the array back to the property, and add to our size counter
values = tmp;
numItems++;
};
//Remove item at index
void remove(int idx)
{
//Can't remove if there are less then 1 items
if(numItems < 1)
return;
//Create a new array of current size - 1
T* tmp = new T[size() - 1];
int c = 0;
//Add items, except for the given index to the new array
for(int i = 0; i < size(); i++)
{
if(i != idx)
{
tmp[c] = values[i];
c++;
}
}
values = tmp;
numItems--;
};
//Return the item at idx
T get(int idx)
{
if(numItems < 1)
//Empty <typename> if there are less then 1 items
return T;
return values[idx];
};
void inverse()
{
T * tmp = new T[numItems];
int c = 0;
for(int i = numItems; i > -1; i--)
{
tmp[c] = values[i];
c++;
}
values = tmp;
};
private:
T* values;
int numItems;
};
#endif //Array_h