在C++中删除动态数组的列,可以通过以下步骤实现:
以下是一个示例代码:
#include <iostream>
void deleteColumn(int**& array, int rows, int& cols, int colToDelete) {
int** newArray = new int*[rows];
for (int i = 0; i < rows; i++) {
newArray[i] = new int[cols - 1];
int newColIndex = 0;
for (int j = 0; j < cols; j++) {
if (j != colToDelete) {
newArray[i][newColIndex] = array[i][j];
newColIndex++;
}
}
}
for (int i = 0; i < rows; i++) {
delete[] array[i];
}
delete[] array;
array = newArray;
cols--;
}
int main() {
int rows = 3;
int cols = 4;
int** array = new int*[rows];
for (int i = 0; i < rows; i++) {
array[i] = new int[cols];
for (int j = 0; j < cols; j++) {
array[i][j] = i * cols + j;
}
}
std::cout << "Original Array:" << std::endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
int colToDelete = 2;
deleteColumn(array, rows, cols, colToDelete);
std::cout << "Array after deleting column " << colToDelete << ":" << std::endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
for (int i = 0; i < rows; i++) {
delete[] array[i];
}
delete[] array;
return 0;
}
这段代码首先创建了一个3行4列的动态二维数组,并填充了一些数据。然后通过调用deleteColumn
函数删除了第2列。最后打印出删除列后的数组。
请注意,这只是一个简单的示例,实际应用中可能需要考虑更多的边界情况和错误处理。此外,为了简化代码,没有使用智能指针或容器类来管理内存,实际应用中建议使用这些工具来提高代码的安全性和可维护性。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云