每次我运行一个名为 Loan &removeFirst () {} 的方法时,我的程序都会崩溃。每当我试图删除我创建的临时贷款结构时,程序就会崩溃。我可以展示容器类的一些背景知识和我的函数的代码:
class ListOfLoans {
public:
//default constructor allocate appropriate heap storage
//store elements on heap array declared like this:
//new Loan*[initial_size];
ListOfLoans(int initial_size = 4) {
elements = new Loan*[initial_size];
numberOfElements = 0;
capacity = initial_size;
index = 0;
}
~ListOfLoans(void) {
cout << "Deleting \n";
delete [] elements;
}
// answer the first element from the list but don't remove it
Loan & first() const {
if (capacity == 0) {
cout << "Attempted on empty list. Exitting!" << endl;
exit;
} else {
return *elements[0];
}
}
// answer the first element from the list and remove it from the list
// if the resulting list is more than three quarters empty release some memory
Loan & removeFirst() {
index--;
if (capacity == 0) {
cout << "Attempted on empty list. Exitting!" << endl;
exit;
}
if(size() < capacity/4) { //shrink the container when 1/4 full
cout << "shrinking\n";
Loan **temp = elements;
elements = new Loan*[capacity/2];
for(index = (numberOfElements - 1); index >= 0; index--) {elements[index] = temp[index];}
capacity /= 2;
delete [] temp; // my program crashes at this line, I want to delete the temp structure
}
return first();
}
private:
Loan ** elements;
int numberOfElements; //number of elements in the list
int capacity; //size of the available array memory
mutable int index; //used to help with the iteration
};
最佳答案
删除指针数组(指向指针的指针)时,您通常会执行以下操作:
for(int i = 0; i < capacity; ++i)
{
delete temp[i];
}
delete [] temp;
如果没有 for 循环,您将泄漏内部指针中的内存。
size() 是否返回 numberOfElements?我在这里担心的是,您的 for 循环将数据从 temp 复制到元素中,并且可能在 temp 范围之外开始。如果是这种情况,您可能正在覆盖内存,这可能是崩溃的根源。为什么不直接从 0 循环到 size()?如果要删除第一个元素,只需使用以下内容复制它:
elements[index] = temp[index+1];
最后,如果您要删除列表中的第一个元素,那么 first() 在内部做了什么?从我上面看到的情况来看,您似乎已经删除了第一个元素,或者本来打算这样做。如果它被删除,它可能会在您返回它时被删除,因此您需要在本地复制该指针并让您的 for 循环删除所有元素并跳过第一个元素,这样您仍然可以返回一些有效的东西!
关于c++ - 如何从 C++ 程序中的容器类中删除第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19216547/