从动态分配的数组中删除
Deleting from a dynamically allocated array
所以我有一个二维数组
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 后复制(在本例中,只需复制指针)所有行下方的所有行。正如 Hayden 在评论中所说,使用 STL 容器可能会更容易。
所以我有一个二维数组
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 后复制(在本例中,只需复制指针)所有行下方的所有行。正如 Hayden 在评论中所说,使用 STL 容器可能会更容易。