template<class T>
class ArrayList {
private:
T * _storage;
int _size;
public:
ArrayList();
ArrayList(const ArrayList&);
~ArrayList();
void addElement(T toAdd);
void addElement(T toAdd, int index);
T popMin();
T popMax();
int getSize() const;
void<T> print() const;
};
cpp file;
i have a bit trouble with the function addElemet(T toAdd)
the function will increase (make new dynamic array with size+1)
then copy the original array to the new array and copy the last elements that we add to the last index .
1 2 3 4 5 6 7 8 9 10 11 12 13 14
template <class T> //add element in the last index
void ArrayList<T>::addElement(T toAdd) {
T* s;
for (int i = 0; i < size; i++) {
s[i] = _storage[i];
}
for (j = size; j < size + 1; j++) {
s[i] = toAdd;
}
delete[]_storage;
_storage = s;
}
Just wondering if you are aware that one shouldn't have template code in the cpp file? That usually results in linker errors. The usual work flow is to put all the template code in the header.
OP: you're also taking on the additional challenge of acquiring resources through the ctor that need to be released before the objects go out of scope calling upon the whole gamut of the rule of three/five (you can google this) – a more tractable alternative might be use a dynamic container like std::vector<T> that can be resized automatically and does all the clean-up after itself or at least by using smart pointers like std::unique_ptr<T[]> - less flexible than std::vector<T> as the arrays will be fixed in size but also cleans up after itself but with deleted copy ctors and copy assignment operators
the function will increase (make new dynamic array with size+1)
Note that this imposes a strict O(n) bound on insertion. It's possible to significantly improve the performance (limiting to a O(1) insertion at the end): See this thread if you're curious: http://www.cplusplus.com/forum/general/212529/