0

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

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

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

还是我必须重新创建大小为 2 的航班数组?

4

2 回答 2

1

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

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;

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

std::vector<std::vector<int>> v(rows);
for(int i=0; i<rows; ++i)
    v[i].resize(cols);
v.resize(v.size()/2);
于 2012-04-08T19:18:40.747 回答
0

好吧,它释放了指向后半部分指针的内存。但是指针本身会留下来,指针数组不会被缩短。

编辑

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

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

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

于 2012-04-08T18:01:24.193 回答