Reputation:
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;
};
Upvotes: 2
Views: 60
Reputation: 9804
Moving the array to a new position invalidates the iterator position
, it points to the old array. So i>position
is undefined behavior.
You should calculate the index before moving the array and set position
at the index in the new array.
template <class T>
class Vector {
public:
typedef T* iterator;
Vector () {
arrayCap=1000;
ditems = new T[arrayCap];
used = 0;
}
T& operator[](unsigned int i) {
return ditems[i];
}
iterator begin () {
return ditems;
}
iterator end () {
return &ditems[used];
}
int size () { return used; }
void deletes(){
used--;
}
iterator insert (iterator position, const T& item) {
if(arrayCap-used<100)
{
auto temp=arrayCap;
arrayCap*=2;
auto index = position - ditems;
auto tempItems=new T[arrayCap];
for(int i=0; i<temp;i++)
{
tempItems[i]= ditems[i];
}
delete [] ditems;
ditems = tempItems;
position = ditems + index;
}
for(Vector<T>::iterator i=&ditems[arrayCap-1]; i>position; i--)
{
*i=*(i-1);
}
used++;
*position = item;
return position;
}
private:
int arrayCap;
T *ditems;
int used;
};
Upvotes: 2