allocating extra memory for a container class.
Posted
by sil3nt
on Stack Overflow
See other posts from Stack Overflow
or by sil3nt
Published on 2010-05-15T13:04:53Z
Indexed on
2010/05/15
13:24 UTC
Read the original article
Hit count: 163
Hey there, I'm writing a template container class and for the past few hours have been trying to allocate new memory for extra data that comes into the container (...hit a brick wall..:| )
template <typename T>
void Container<T>::insert(T item, int index){
if ( index < 0){
cout<<"Invalid location to insert " << index << endl;
return;
}
if (index < sizeC){
//copying original array so that when an item is
//placed in the middleeverything else is shifted forward
T *arryCpy = 0;
int tmpSize = 0;
tmpSize = size();
arryCpy = new T[tmpSize];
int i = 0, j = 0;
for ( i = 0; i < tmpSize; i++){
for ( j = index; j < tmpSize; j++){
arryCpy[i] = elements[j];
}
}
//overwriting and placing item and location index
elements[index] = item;
//copying back everything else after the location at index
int k = 0, l = 0;
for ( k =(index+1), l=0; k < sizeC || l < (sizeC-index); k++,l++){
elements[k] = arryCpy[l];
}
delete[] arryCpy;
arryCpy = 0;
}
//seeing if the location is more than the current capacity
//and hence allocating more memory
if (index+1 > capacityC){
int new_capacity = 0;
int current_size = size();
new_capacity = ((index+1)-capacityC)+capacityC;
//variable for new capacity
T *tmparry2 = 0;
tmparry2 = new T[new_capacity];
int n = 0;
for (n = 0; n < current_size;n++){
tmparry2[n] = elements[n];
}
delete[] elements;
elements = 0;
//copying back what we had before
elements = new T[new_capacity];
int m = 0;
for (m = 0; m < current_size; m++){
elements[m] = tmparry2[m];
}
//placing item
elements[index] = item;
}
else{
elements[index] = item;
}
//increasing the current count
sizeC++;
my testing condition is
Container cnt4(3);
and as soon as i hit the fourth element (when I use for egsomething.insert("random",3);
) it crashes and the above doesnt work. where have I gone wrong?
© Stack Overflow or respective owner