从动态分配的数组中删除

Deleting from a dynamically allocated array

本文关键字:删除 数组 动态分配      更新时间:2023-10-16

我有一个2D数组

char **m_data

这个数组的宽度为width,高度由一个叫做m_heigths的向量给出。

// Remove blank space where necessary
// Iterate through every row
for (int x=0; x<m_width; ++x){
// count number of spaces
    int spaces=0;
    // iterate through the given row
    for (int y=0; y<m_heigths[x]; ++y){
    // if space is occupied by a black space increment count
        if (m_data[x][y]==' '){
            ++spaces;
        }
    }
    // check if entire column is just a bunch of blanks
    if (spaces==m_heigths[x]){
        // get rid of blanks
        delete [] m_data[x];
    }
}

所以我想找一个只有一堆空格的列并删除它。但这似乎不起作用,空格留在那里。有人能帮我吗?

delete只释放已分配的内存。要真正删除该行,您需要在调用delete之后将下面的所有行向上复制(在本例中,只需复制指针)1。就像Hayden在评论中说的,使用STL容器可能会更容易。