在c++中复制数组的内容到调整大小的数组

Copying content of array to resized array in C++

本文关键字:调整 数组 c++ 复制数组      更新时间:2023-10-16

我在这里搜索了很多主题,但他们似乎没有确切地回答我。

我试图在c++中做一些动态重新分配数组。我不能使用STL库中的任何东西,因为我需要在作业中使用它,其中STL (vectors,…)是明确禁止的。

到目前为止,我尝试用这样的代码来详细说明 :
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;

这似乎是可行的,但困扰我的是过多的迭代次数。难道就没有更聪明的办法吗?显然,我要处理比这大得多的数组。不幸的是,I 不得不处理数组。

edit:当我尝试做items = temp;而不是

for (int i = 0; i < 10; i++) items[i] = temp[i];并尝试std::cout所有元素,我最终失去了前两个元素,但valgrind正确打印它们

是的,第一个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;

STL的容器是为了简化这样的工作而制作的。这很乏味,但是当您需要使用C -arrays时,没有太多的选择。

的删除
delete [] items; 

是必要的,当您放弃对数组的引用时,您可以在

中赋值一个新的引用。
items = new int [10];

将导致内存泄漏,所以这是必要的。