C++Stack栈类模版实例详解

C++Stack栈类模版实例详解 栈的实现方式分为3种基于静态数组实现,内部预设一个很大的数组对象, 实现简单缺点是空间受限。基于动态数组实现,内部预设一个容量值,然后分配一段内存空间数组,如果入栈大于默认容量值时,则再次扩大分配新的内存数组,并将旧数组拷贝至新数组及释放旧数组.基于双向循环链表实现栈的函数需要实现如下所示:T pop() :出栈并返回栈顶元素void push(const T t) :入栈const T top() const :获取const类型栈顶元素T top() :获取栈顶元素int length() const:获取数量(父类已经实现)void clear():清空栈(父类已经实现)本章,我们实现的栈基于动态数组实现,它的父类是我们之前实现的Vector类2.栈实现代码如下所示:123456789101112131415161718192021222324252627282930313233343536373839404142#ifndef Stack_H#define Stack_H#include throw.h// throw.h里面定义了一个ThrowException抛异常的宏,如下所示://#include iostream//using namespace std;//#define ThrowException(errMsg) {cout__FILE__ LINE__LINE__: errMsgendl; (throw errMsg);}#include Vector.htemplateclassTclassStack :publicVectorT{public:T pop(){if(VectorT::isEmpty()) {// 如果栈为空,则抛异常ThrowException(Stack is empty ...);}T t VectorT::data()[VectorT::length() - 1];VectorT::resize(VectorT::length() - 1);returnt;}// 入栈,实际就是append尾部添加成员voidpush(constT t){VectorT::append(t);}T top(){if(VectorT::isEmpty()) {ThrowException(Stack is empty ...);}returnVectorT::data()[VectorT::length() - 1];}constT top()const{if(VectorT::isEmpty()) {ThrowException(Stack is empty ...);}returnVectorT::data()[VectorT::length() - 1];}};#endif // Stack_H3.代码测试1234567891011121314intmain(intargc,char*argv[]){Stackint stack;cout******* current length:stack.length()endl;for(inti 0; i 5; i) {coutstack.push:iendl;stack.push(i);}cout******* current length:stack.length()endl;while(!stack.isEmpty()) {coutstack.pop:stack.pop()endl;}return0;}运行打印:总结本篇文章就到这里了希望能够给你带来帮助