2013-03-27 56 views
0

我在這裏搜索了很多主題,但他們似乎沒有完全回答我。在C++中將數組的內容複製到已調整大小的數組

我想在C++中做一些動態的重新分配od數組。我不能使用STL庫中的任何東西,因爲我需要在功能明確禁止STL(矢量,...)的作業中使用它。

到目前爲止,我已經試過用代碼來闡述這樣的:

int * items = new int[3]; //my original array I'm about to resize 
int * temp = new int[10]; 
for (int i = 0; i < 3; i++) temp[i] = items[i]; 

delete [] items; //is this necessary to delete? 
items = new int [10]; 
for (int i = 0; i < 10; i++) items[i] = temp[i]; 
delete [] temp; 

這似乎工作,但什麼困擾我的是迭代的數量過多。無論如何,這無法做到更聰明嗎?顯然,我正在處理比這更大的數組。不幸的是,我必須與數組工作。

編輯:當我嘗試做items = temp;,而不是

for (int i = 0; i < 10; i++) items[i] = temp[i];並嘗試std::cout我的所有元素,我最終失去了前兩個元素,但的valgrind正確打印它們。

+0

當這是爲家庭作業,更聰明的事情將是封裝它,即重寫你需要的std :: vector的部分...取決於你的「stl」的定義是什麼,你可能能夠使用像std :: copy來封裝複製過程。 – PlasmaHH 2013-03-27 11:27:30

+0

請記住,指針是正常的變量,因此可以重新分配... – 2013-03-27 11:28:46

+2

有一段時間,因爲我觸摸C++,但是,你需要複製項目[] temp []然後從temp [] abck項目[]?難道你不能只是創建一個新的指針項目[] - 'int * temp = items;'然後重新創建項目 - 'items = new int [10]'。將你的副本從'temp'複製到'items' - 可能要查看'memcopy'函數或'std :: copy'函數來最有效地執行此操作。然後刪除'temp'。 – wmorrison365 2013-03-27 11:34:39

回答

5

是的,第一個delete[]是必要的。沒有它,你會泄漏記憶。

至於首先delete[]後到來的代碼,這一切可以替換爲:

items = temp; 

這將使items指向你剛纔所填充的十個元素的數組:

int * items = new int[3]; //my original array I'm about to resize 
int * temp = new int[10]; 
for (int i = 0; i < 3; i++) temp[i] = items[i]; 
delete [] items; //delete the original array before overwriting the pointer 
items = temp; 

最後,當你完成數組時,不要忘記delete[] items;

+0

奇怪,我有'items = temp;'的一些錯誤。我不知何故失去了前兩個元素。 – Saraph 2013-03-27 11:32:26

+0

@NPE你沒有混淆序列嗎?更好地寫下代碼而不是描述它 – 4pie0 2013-03-27 11:33:38

0

STL的容器是爲了緩解這樣的工作。這是乏味的,但沒有太多的選擇,當你需要使用C-陣列。

delete [] items; 

缺失是必要的,因爲當你放棄參考數組,你將與分配在

items = new int [10]; 

一個新的參考會導致內存泄漏呢,所以這是必要的。

相關問題