#ifndef STACK_HPP
#define STACK_HPP
#include <deque>
#include <exception>
template <class T>
class stack
{
 protected:
  std::deque<T> c;
 public:
  class ReadEmptyStack : public std::bad_exception
  {
  public:
   virtual const char* what() const throw()
   {
    return "read empty stack";
   }
  };

  typename std::deque<T>::size_type size() const
  {
   return c.size();
  }

  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

测试抛出异常:

#include <iostream>
//#include <stack>
#include "stack.hpp"
using namespace std;
int main()
{
 try{
  stack<int> st;
  st.push(1);
  st.push(2);
  st.push(3);
  cout<<st.top()<<' ';
  st.pop();
  cout<<st.top()<<' ';
  st.pop();
  
  st.top()=77;
  st.push(4);
  st.push(5);
  st.pop();

  cout<<st.pop()<<' ';
  cout<<st.pop()<<endl;
  cout<<st.pop()<<endl;


//   while(!st.empty())
//   {
//    cout<<st.top()<<' ';
//    st.pop();
//   }
//  
 }
 catch(const exception& e){
  cerr<<"EXCEPTION: "<<e.what()<<endl;
 }
 

}

posted on 2010-04-13 18:54  蓝牙  阅读(199)  评论(0编辑  收藏  举报