指针数组大小增加-C ++

问题描述

我正在创建一个Min Heap类(用于实践),并且可以完全正常工作,但是,对我来说,我的指针数组的增加容量函数(该数组持有堆数组)可能会导致内存泄漏。 (不好意思,我的编码)。在下面,我显示了我的函数,构造函数和私有成员init,但是,这并不是在代码中实际构造的方式,只是为了方便编写帖子。

int* heap; // init as a private member

MinHeap() {
   this->total_capacity = 10; // init in default constructor
   heap = new int[total_capacity];
}

// if total capacity is reached:
 // creates a larger array and copies all elements over to it
 void ensureExtraCapacity() {
    if (length == total_capacity) {
       total_capacity *= 2;
       int* temp = new int[total_capacity];
       for (int i = 0; i < length; i++)
          temp[i] = heap[i];
       heap = temp;
       delete[] temp; // <= this is causing me issues
       cout << "Capacity added." << endl;
    }
 }
  • 长度是一个整数,可以跟踪堆中有多少个数字

我试图删除它,但是,它最终要么从新数组中删除了新数字,要么以两个方式添加了两个零,这不好。

with the "delete[] temp" without the "delete[] temp"

2件事:

  • 我知道我可以使用改变生活的矢量,但我想使用指针数组进行练习。
  • 如果有更好的方法可以做到这一点(例如使用诸如copy或std:array之类的STL函数,请让我知道,但是我仍然想要对此的答案)

P.S:对不起,如果重复的话,我环顾四周发誓。

P.S:如果您知道有任何资源可以更好地利用内存处理和指针(甚至是STL库),请也将其链接,谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)