Inside the insert function, I use dynamic memory allocation with the arrays ditems and tempItems.
Where I am using tempItems to be an array twice as big as ditems and also store all the items from ditems temporary; and then deleting and assigning ditems equaling tempItems
The code complies fine, but when testing it with say enough data requiring ditems to store 2000 elements, it appears that the ditems array is not getting any bigger.However if I was to set (arrayCap=2001;) in the constructor, then there is no problem.
I am new to using dynamic arrays and looking at other code using dynamic arrays, it doesn't look like I had made any mistakes. I can't use vectors for this task, so I am stuck with dynamic arrays, but I am not sure what is wrong here.
template <class T>
class Vector {
public:
typedef T* iterator;
Vector () {
arrayCap=1000;
ditems = new T[arrayCap];
}
T& operator[](unsigned int i) {
return ditems[i];
}
iterator begin () {
used=0;
return &ditems[used];
}
iterator end () {
return &ditems[used];
}
int size () { return used; }
void deletes(){
used--;
}
iterator insert (iterator position, const T& item) {
if(arrayCap-used<100)
{
temp=arrayCap;
arrayCap=2*arrayCap;
tempItems=new T[arrayCap];
for(int i=0; i<temp;i++)
{
tempItems[i]= ditems[i];
}
delete [] ditems;
ditems=tempItems;
}
for(Vector<T>::iterator i=&ditems[arrayCap-1]; i>position; i--)
{
*i=*(i-1);
}
used++;
*position= item;
return position;
}
private:
int arrayCap,temp;
T *ditems;
T *tempItems;
int used;
};
begin()andend()return the same thing. Your range will always appear empty.tempItemsshould be a local variable in theinsertmethod. There's no reason to make it a class variable. Same is true of thetempvariable as well.usedvariable is incorrect, it should be set in the constructor not in thebeginmethod. Thebeginmethod should bereturn &ditems[0];beginmethod you setusedto zero. In other words calling begin sets the size of your vector to zero. Obviously that's a bug.