C++如何删除动态分配的2d数组中的特定行或列?

Dph*_*han 0 c++ multidimensional-array dynamic-memory-allocation delete-operator

所以,我以这种方式动态分配了一个二维数组:

int rs, co;
cin >> ro;
cin >> co;

int **array = new int* [ro];

for(int i = 0; i < ro; i++){
    array[i] = new int [co];
}
Run Code Online (Sandbox Code Playgroud)

我填写了:

for(int i = 0; i < ro; i++){
    for(int j = 0; j < co; j++){
        cout << "Row: " << i << " Column: " << j << "  : ";
        cin >> *(*(array + i) + j);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:如何释放用户给出X的X行或列?我知道我应该使用"删除"命令,但我无法理解

gsa*_*ras 5

您无法删除列,但可以删除行.

如果这对您没有意义,请尝试阅读我的2D动态数组(C).关注这个数字:

在此输入图像描述

我知道我的链接是在C中,但是你尝试做的事情让我想起了C.在C++中,你可以用一个std::vector<int>代替.


我假设你知道你可以写:

array[i][j]
Run Code Online (Sandbox Code Playgroud)

代替:

*(*(array + i) + j)
Run Code Online (Sandbox Code Playgroud)

删除具有两行的矩阵的第一行的示例.

delete [] array[0];
int **tmp = new int*[1];
tmp[0] = array[1];
delete [] array;
array = tmp;
Run Code Online (Sandbox Code Playgroud)

一般例子:

#include <iostream>
using namespace std;

int main(void) {
    int ro = 3, co = 2;
    int **array = new int* [ro];

    for(int i = 0; i < ro; i++){
        array[i] = new int [co];
    }
    // fill and print the matrix
    for(int i = 0; i < ro; i++){
        for(int j = 0; j < co; j++) {
            array[i][j] = i;
            cout << array[i][j] << " ";
        }
        cout << endl;
    }

    int rowToDel = 1;
    delete [] array[rowToDel];
    int **tmp = new int*[ro - 1];
    int tmpI = 0;
    for(int i = 0; i < ro; ++i)
        if(i != rowToDel)
            tmp[tmpI++] = array[i];
    delete [] array;
    array = tmp;
    ro = ro - 1;

    cout << "Array after deleting " << rowToDel << "-th row\n";
    for(int i = 0; i < ro; i++){
        for(int j = 0; j < co; j++) {
            cout << array[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

0 0 
1 1 
2 2 
Array after deleting 1-th row
0 0 
2 2
Run Code Online (Sandbox Code Playgroud)