gpt4 book ai didi

c++ - 数组,removeFirst() 不工作?

转载 作者:行者123 更新时间:2023-11-28 07:22:32 24 4
gpt4 key购买 nike

我创建了一个应该删除数组的第一个元素的方法,但是当我运行我的代码时,调试器出现故障,我不确定为什么。

这是我的 removeFirst() 方法:

Loan & ListOfLoans ::  removeFirst(){
index = 0;
//determine if the container needs to be shrunk
if((numberOfElements < capacity/4) && (capacity >= 4)){ // shrink container when array is 1/4 full
cout<<"shrinking array! \n";
Loan ** temp = elements;
elements = new Loan * [numberOfElements/2];
//copy temp array to elements
for(int i = 0; i<numberOfElements; i++){
temp[i] = elements[i];
numberOfElements = numberOfElements/2;
delete [] temp;
}
}
numberOfElements--;
return **elements;
}

还有我的头文件:

#include <iostream>
#include "loan.h"

using namespace std;

class ListOfLoans {

public:
ListOfLoans(int initial_size=4);

~ListOfLoans(void);


void add(Loan & aLoan);
Loan & first() ;
Loan & removeFirst();
// 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 & removeLast();
// answer the last element from the list and remove it from the list
// if the resulting list is more than three quarters empty release some memory
Loan & next();
int size();

private:
Loan ** elements; //actuall stuff in the array m_pnData;
int numberOfElements; //number of elements in the list stize of the array? m_nLength
int capacity; //size of the available array memory
int index; //used to help with the iteration
};

最佳答案

尝试将 delete [] temp; 移到 for 循环下。

看起来一个问题可能是 delete [] temp; 在 for 循环中被重复调用。通过循环的第一次迭代,与 temp 关联的内存将被释放。循环中的后续迭代将访问释放的内存。

可能还有其他问题。查看调试器的输出会很有帮助。

关于c++ - 数组,removeFirst() 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19214314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com