在c++中复制数组的内容到调整大小的数组
Copying content of array to resized array in C++
我在这里搜索了很多主题,但他们似乎没有确切地回答我。
我试图在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];
将导致内存泄漏,所以这是必要的。
相关文章:
- 为char数组调整zlib-zpipe
- 当您在此单词中搜索单词时调整字符数组的大小?
- 调整大小和复制哈希表数组中的元素
- 尝试将数组大小调整为 -1
- 将动态分配的数组的大小调整为较小的大小C++
- 我的C++程序有问题.涉及动态调整整数数组的大小
- 通过新的后传递后创建的动态数组的错误以调整函数
- 在哈希表中调整字符串数组的大小
- 与教科书上关于未调整大小的数组初始化C++句子的混淆
- 调整双指针数组C++大小
- 调整结构/字符数组的大小(以减少内存使用)
- 我的数组大小调整代码在新数据上引发异常[size_t]
- 如何使用3D char数组调整双指针2D char阵列的大小
- C++ 数组将所有值调整相同的量
- 调整动态数组大小时保留用户输入的值的问题
- C++我需要能够调整动态数组的大小
- 如何调整属于类的唯一指针的字符数组的大小.它必须在程序的整个生命周期中保持活力
- 调整小于连续数组的 C++ 矢量大小
- 我需要调整指针数组的大小
- C++调整动态数组的大小