2010-05-15 52 views
0

嘿,那裏,我正在寫一個模板容器類,並在過去的幾個小時一直試圖分配新的內存額外的數據進入容器(...擊中磚牆..:|)爲容器類分配額外的內存

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++; 

我的測試條件是 集裝箱CNT4(3); 只要我碰到第四個元素(當我用於例如something.insert("random",3);)它崩潰,並且上述不起作用。我哪裏錯了?

回答

0

幾件事情沒有什麼太大的意義對我說:

if (index+1 > capacityC){ 

應該不就是:

if (index >= capacityC){ 

而且,當你長大的陣列,我不明白爲什麼你正在進行兩次複製。切忌:

delete[] elements; 
elements = 0; 

是:

delete[] elements; 
elements = tmparray2; 
0

注意new T[n]可能不是你真正想要在T容器是什麼,因爲這已經創建n個對象T。你真正想要的是保留內存,然後在稍後的某個時間點構建內存中的T類型的對象。

T* data = static_cast<T*>(operator new[](n * sizeof(T)); // allocate memory 
// ... 
new(&data[size]) T(arguments); // construct T object in-place 
++size; 

爲了破壞容器,你必須顛倒過程:逐個銷燬對象,然後釋放內存。

while (size) data[--size].~T(); // destruct T object in-place 
operator delete[](data);   // release memory