63,594
社区成员




//vecStack.h
#ifndef VEC_STACK_H
#define VEC_STACK_H
#include <vector>
using std::vector;
template<class T, int capacity = 30>
class vecStack
{
private:
vector<T> pool;
public:
vecStack()
{
pool.reserve(capacity);
}
void Clear()
{
pool.clear();
}
bool isEmpty() const
{
return pool.empty();
}
T& topEl()
{
return pool.back();
}
T pop()
{
T el = pool.back();
pool.pop_back();
return el;
}
void push(const T& el)
{
pool.push_back(el);
}
};
#endif
//main.cpp
#include <iostream>
#include "Stack.h"
using namespace std;
enum ResultCode {Nomemory,OutOfBounds,Underflow,Overflow,Duplicate};
void main()
{
try
{
SeqStack<double> dstk(2); //构造一个容量为2的双精度数栈
dstk.Push(3.7);
dstk.Push(8.8); //向栈中依次加入3.7和8.8
cout<<dstk; //输出栈中元素
dstk.Pop();
if(dstk.IsEmpty()) //判定栈是否为空
cout<<"Is empty!"<<endl;
else
cout<<"Is not empty!"<<endl;
dstk.Pop(); //两次删除运算,将产生下溢异常
dstk.Pop();
}
catch(ResultCode err)
{
switch(err) //根据异常类别,处理异常
{
case Overflow:
cout<<"Overflow!"<<endl;
break;
case Underflow:
cout<<"Underflow!"<<endl;
break;
}
}
}
//Stack.h
#include <ostream>
//ostream是包含在头文件ostream里的,也是标志符,要使用命名空间或者std::ostream才可以用
using namespace std;
//基类Stack的定义
template <class T>
class Stack
{
public:
virtual void Push(const T&x)=0;
virtual void Pop()=0;
virtual T Top()const=0;
virtual bool IsEmpty()const=0;
virtual bool IsFull()const=0;
};
//派生类SeqStack的定义
template <class T>
class SeqStack:public Stack<T>
{
public:
SeqStack(int mSize);
~SeqStack(){delete []s;}
bool IsEmpty() const {return (top==-1);}
bool IsFull() const {return (top==maxSize-1);}
void Push(const T&x);
void Pop();
T Top()const;
void Output(ostream& out)const;
private:
//void Output(ostream& out)const;
T *s;
int maxSize;
int top;
friend ostream &operator<<(ostream &out,const SeqStack<T>&s);
};
//Stack.cpp
//#include "Stack.h"
//构造函数的实现
template <class T>
SeqStack<T>::SeqStack(int mSize)
{
maxSize=mSize;
s=new T[maxSize];
top=-1;
}
//进栈函数的实现
template <class T>
void SeqStack<T>::Push(const T &x)
{
if (IsFull()) throw Overflow;
s[++top]=x;
}
//出栈函数的实现
template <class T>
void SeqStack<T>::Pop()
{
if (IsEmpty()) throw Underflow;
top--;
}
//返回栈顶元素的函数的实现
template <class T>
T SeqStack <T>::Top()const
{
if (IsEmpty()) throw Underflow;
return s[top];
}
//输出栈中所有元素的函数实现
template <class T>
void SeqStack <T>::Output(ostream &out)const
{
int i=top;
out<<endl<<"Stack contains:";
while (i!=-1) out<<s[i--]<<" ";
out<<endl;
}
//
template <class T>
ostream &operator<<(ostream& out,const SeqStack<T>&s)
{
s.Output(out);
return out;
}