#ifndef STACK_H
#define STACK_H
#include <deque>
#include <exception>
template<class T>
class Stack
{
protected:
std::deque<T> c;
public:
class ReadEmptyStack : public std::exception //exception 是标准异常,
{
public:
virtual const char * what() const throw()
{
return "read empty stack 堆栈是空的";
}
};
bool empty() const
{
return c.empty();
}
void push(const T& elem)
{
c.push_back(elem);
}
T pop() // 抛出数据,
{
if(c.empty())
{
throw ReadEmptyStack();
}
T elem(c.back());
c.pop_back();
return elem;
}
T& top() // 读数据,
{
if(c.empty())
{
throw ReadEmptyStack();
}
return c.back();
}
};
#endif
<pre name="code" class="cpp">#include <iostream>
#include "Stack.h"
using namespace std;
int main()
{
try
{
Stack<int> s;
s.push(4);
s.push(7);
cout << "pop : " << s.pop() << endl;
cout << "top: " << s.top() << endl;
cout << "pop: " << s.pop() << endl;
cout << "top: " << s.top() << endl;
}
catch(const exception& e)
{
cerr << "发生异常:" << e.what() << endl;
}
cout << "xiao cui " << endl;
return 0;
}