C++,通过删除 [] x[i] 来缩小动态数组

c++, minify dynamic array by delete [] x[i]

本文关键字:缩小 动态 数组 删除 C++      更新时间:2023-10-16

我有一个大小为 4(4 行)的 2D 数组。要使数组大小为 2(2 行),我可以使用以下内容吗?(对于我们的硬件分配细节没有指定,代码应该适合常见的C ++标准)

我正在删除数组的后半部分。

const int newSize = flightsArraySize/2;
for(int i = newSize-1; i < flightsArraySize-1; i++)
   delete [] flights[i];

还是必须重新创建大小为 2 的飞行数组?

假设您已经使用 new 创建了一个 2D 数组,如下所示:

int **arr = new int*[rows];
for(int i=0; i<rows; ++i)
    arr[i] = new int[cols];

然后要调整它的大小,您必须执行以下操作:

int newRows = rows/2;
// Create a new array for the right number of rows.
int **newArr = new int*[newRows];
// Copy the rows we're keeping across.
for(int i=0; i<newRows; ++i)
    newArr[i] = arr[i];
// Delete the rows we no longer need.
for(int i=newRows; i<rows; ++i)
    delete[] arr[i];
// Delete the old array.
delete[] arr;
// Replace the old array and row count with the new ones.
arr = newArr;
rows = newRows;

但说真的,如果你只使用vector,这一切都会容易得多:

std::vector<std::vector<int>> v(rows);
for(int i=0; i<rows; ++i)
    v[i].resize(cols);
v.resize(v.size()/2);

好吧,它解除了指向指针后半部分的内存。但是poiters本身会留下来,指针阵列不会缩短。

编辑

哦,对不起。这似乎是一个错误。如果您有这样的代码:

int **ptr = new int*[4];
for(int i = 0; i < 4; i++)
{
    ptr[i] = new int[4];
}

然后当你输入

delete[] ptr[3];

它将删除整个数组,因此您可以像这样创建新的数组:

ptr[3] = new int[any_number];

这是你的意思吗?对不起,我读得太快了...