我的任务是实现一个具有给定容量的堆栈(基于数组),当在堆栈已满后尝试添加另一个元素时,该堆栈将按常量值增长(我使用了 100)。
我相信这里的问题在于我的 push() 函数,它向堆栈添加了 100 个元素......可能是语法,但我完全不确定为什么我的程序无法执行。
template<class Type>
class ArrayStack{
enum {default_cap=100};
private:
Type* S; //array storing elements
int CAP; //capacity of stack
int TOP; //top element of stack
public:
ArrayStack(int defc = default_cap); //constructor with default parameter
~ArrayStack(){} //is "delete [] S;" supposed to go in here? not sure
bool isEmpty() const { return (TOP<0); }//is the stack empty?
int size() const { return (TOP+1); }
const Type& top(){ return S[TOP];} //has exception handling, not displayed
Type pop() {--TOP;} //removes top element
//here's the function that concerns me:
//--------------------------------------------
void push (const Type& e){
if(size() == CAP) {
Type* Snew = new Type[CAP+100];
for(int i = 0; i < CAP; i++){
Snew[i] = S[i];
}
delete [] S;
++CAP;
S = Snew;
}
S[++TOP] = e;
}
//--------------------------------------------
//other functions...
};
//constructor:
template<typename T> ArrayStack<T>::ArrayStack(int d)
: S(new T[d]), CAP(d), TOP(-1){}
有点难以评论,因为您只提供了部分代码,并且没有演示用法(例如,使用 main() 函数)。
然而,push() 函数的一个明显问题 [我注意到 Roger Rowland 在他的评论中也发现了] 是它增加了 100 个分配的大小,但只增加了 CAP。 因此,它将向数组添加 100 个元素,但仅报告使用添加的第一个元素的能力。
pop() 函数还会丢弃顶部元素,并且不返回它。 如果调用方尝试使用 pop() 的返回值 - 并且堆栈类型的用户通常希望能够使用他们弹出的值 - 结果将是未定义的行为。
您的析构函数肯定需要使用运算符删除,除非您以其他方式清理动态分配的内存(并且您没有显示任何类似内容)。 运算符 new 的全部要点是,在相应的运算符删除之前不会释放内存。 如果您忘记这样做,它不会被神奇地清理,并且只要您的程序运行,(至少)就会出现内存泄漏。
如果你想更安全地做事,请使用 std::vector 而不是指针(并避免直接使用运算符 new)。