C++,通过删除 [] x[i] 来缩小动态数组
c++, minify dynamic array by delete [] x[i]
我有一个大小为 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];
这是你的意思吗?对不起,我读得太快了...
相关文章:
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- C++中的动态铸造故障
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 内联映射初始化的动态atexit析构函数崩溃
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 控制允许动态运行c++的并发操作数
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 输出没有重复元素的动态数组(收缩数组)C++
- C++为线程工作动态地分割例程
- 正在插入动态数组
- 我无法缩小此分段错误的原因
- 在c++中使用动态分配的问题
- C++中的动态对象与非动态对象
- 如何在动态数组上使用搜索函数
- 如何在C++中增大和缩小双指针动态数组
- 套接字动态绑定到缩小范围
- C++,通过删除 [] x[i] 来缩小动态数组