Template class of Array

Write your question here.
header file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  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;

}
Last edited on
You haven't allocated any memory for the new array. At line 5, s is uninitialised, so s[i] will be an undefined memory location.
T *s?
hmm how should i do it ?
i try to google this for an hour any idea or can you direct me?
T *s

That just declared a pointer. Nothing else. It doesn't allocate memory. It doesn't set that pointer to any value.

hmm how should i do it ? 

What's wrong with doing it the same way as you allocate the memory for the original array? (You don't show us how you do that.)
Last edited on
@darje

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.

Good Luck !!
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/
Topic archived. No new replies allowed.