用C++實現一個簡單的棧,基於數組來實現。
#ifndef _ARRAYSTACK_
#define _ARRAYSTACK_
#include <iostream>
#include <stdexcept>
using namespace std;
template <typename T>
class ArrayStack
{
public:
explicit ArrayStack(int maxSize=100) : _size(0),_maxSize(maxSize)
{
_values = new T[_maxSize];
}
~ArrayStack()
{
delete [] _values;
}
ArrayStack(const ArrayStack& rhs) : _values(NULL)
{
operator=(rhs);
}
const ArrayStack& operator= (const ArrayStack& rhs)
{
if( this != &rhs )
{
_size = rhs._size;
_maxSize = rhs._maxSize;
delete [] _values;
_values = new T[_maxSize];
for(int i=0;i<_size;++i)
_values[i] = rhs._values[i];
}
return *this;
}
T Pop()
{
if(IsEmpty())
throw new logic_error("Stack is empty");
return _values[--_size];
}
T& Top() const
{
if(IsEmpty())
throw new logic_error("Stack is empty");
return _values[_size - 1];
}
void Push(const T& value)
{
if(IsFull())
throw overflow_error("Stack is full");
_values[_size++] = value;
}
bool IsEmpty() const
{
return _size==0;
}
int Size() const
{
return _size;
}
bool IsFull() const
{
return _size == _maxSize;
}
void Clear()
{
_size = 0;
}
void Print() const
{
cout << "IsEmpty=" << IsEmpty() << endl;
cout << "IsFull=" << IsFull() << endl;
cout << "Size=" << _size << endl;
cout << "MaxSize=" << _maxSize << endl;
for(int i=0;i<_size;++i)
cout<< _values[i] << ",";
cout << endl;
}
private:
int _size;
int _maxSize;
T* _values;
};
#endif /* _ARRAYSTACK_ */
#include "ArrayStack.cpp"
void ArrayStackTest1();
void Test( void (*fp)() );
int main(int argc, char** argv)
{
Test(ArrayStackTest1);
return 0;
}
void ArrayStackTest1()
{
ArrayStack<int> s;
s.Print();
s.Push(5);
s.Print();
s.Push(4);
s.Push(3);
s.Push(2);
s.Push(1);
s.Print();
cout << "Top=" << s.Top() << endl;
cout << "Pop=" << s.Pop() << endl;
s.Print();
for(int i=0;i<96;++i)
s.Push(i+5);
s.Print();
s.Push(110);
}
void Test( void (*fp)() )
{
try
{
fp();
}
catch(out_of_range e)
{
cout<< "Catch Exception:" << e.what() << endl;
}
catch(overflow_error e)
{
cout<< "Catch Exception:" << e.what() << endl;
}
catch(logic_error e)
{
cout<< "Catch Exception:" << e.what() << endl;
}
}