C ++在2D动态数组中删除和压缩偶数行

时间:2016-06-14 23:00:05

标签: c++ arrays dynamic 2d

我需要一些帮助

该计划必须:

•删除所有偶数行

•将剩余的行压缩到2D数组的顶部

https://gyazo.com/64954d5a5ace39e7bb4264f2e2a9ecdf

CODE:

int main(int argc, char ** argv){
   int ** array2d;

   int size = 10;
   array2d = new int *[size];
   cout << "***** Before Compaction ******" << endl;
   for (int i = 0; i < size; i++) {
      array2d[i] = new int[size];
      cout << "ROW " <<i << ":";
      for (int j = 0; j < size; j++) {
         array2d[i][j] = i;
         cout << " "<< array2d[i][j];
      }
      cout << endl;
   }

   //NEED HELP WITH THIS PART DOWN HERE


   for (int i = 0; i < size; i++) {
      if (i % 2 == 0) { // delete the even rows
         delete[] array2d[i];
         array2d[i] = NULL;
      }
      // for each row in the first half, redirect the pointer
      // to the next odd row
      if(i<size/2){
         array2d[i] = array2d[2 * i + 1];
         array2d[2 * i + 1] = NULL;

      }

      cout << endl;
   }
   return 0;
}

1 个答案:

答案 0 :(得分:0)

  if (i % 2 == 0) { // delete the even rows
     delete[] array2d[i];
     array2d[i] = NULL;
  }

i == 0对应第一行。我想你可能想把它改成:

  if ((i+1) % 2 == 0) { // delete the even rows
     delete[] array2d[i];
     array2d[i] = NULL;
  }

然后,

     array2d[i] = array2d[2 * i + 1];
     array2d[2 * i + 1] = NULL;

需要:

     array2d[i] = array2d[2 * i];
     array2d[2 * i] = NULL;

更新

你所拥有的和我建议的问题是你正在泄漏记忆。当你使用:

     array2d[i] = array2d[2 * i];

array2d[i]分配的内存丢失。你无法释放那段记忆。您可能希望交换指针值以允许您释放所有内存。

     int* temp = array2d[i];
     array2d[i] = array2d[2 * i];
     array2d[2 * i] = temp;