我正在尝试调整堆对象的大小,以便在用户尝试构建超出堆容量的堆时程序可以继续。我能够返回一个指向新堆的指针,但这不适用于我程序的其他部分。我想直接更改我的指针指向p
的位置。这是我的尝试。它编译但指针仍然指向旧位置。请帮我修复这段代码,这样我就不必从我的BuildHeap
函数中返回一个指针。我会发布我所有的代码,但这是家庭作业,我不希望我的工作被复制。
HEAP* Initialize(int n) {
HEAP* p;
p = new HEAP;
p->size = 0;
p->capacity = n;
p->H = new ELEMENT[p->capacity+1]; //first address not used, so we need +1 here
return p;
}
void Resize(int n, HEAP*& ptr) { //pass pointer by reference
ptr = Initialize(n);
}
void BuildHeap(HEAP* p, ELEMENT *A) {
int length = A[0].key; //length = array size stored in A[0]
if(length <= p->capacity) {
p->size = length;
for(int i = 1; i <= length; i++) {
p->H[i].key = A[i].key; //copy ELEMENT array into heap object's H array
}
for(int i = (length) / 2; i >= 1; i--)
MaxHeapify(p, i);
}
else {
cout << "Error: Heap capacity exceeded. Resizing heap.\n";
Resize(length, p); //initialize a new, larger heap
BuildHeap(p, A);
cout << "Heap built with new heap capacity of " << p->capacity << ".\n";
}
}
编辑:我能够通过在调用 BuildHeap 之前检查是否需要更改指针来解决我的问题:
if(length > p->capacity) { //resize heap if capacity is exceeded
cout << "Error: Heap capacity exceeded. Resizing heap.\n";
p = Initialize(length);
}
BuildHeap(p, A);