stack in c++

来源:互联网 发布:淘宝网-淘我喜欢首页 编辑:程序博客网 时间:2024/05/01 06:50

stack在c++stl中作为特殊容器存在,其实现多为单纯地把各项操作转化为内部容器的对应调用

下面是其简单实现

头文件

#ifndef _STACK_H#define _STACK_H#include<deque>#include<exception>template <typename T>class Stack{  protected:  std::deque<T> c;  public:  class ReadEmptyStack:public std::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 "stack_c++.h"#include<iostream>using namespace std;int main(){try{Stack<int>st;st.push(1);st.push(2);st.push(3);cout<<st.pop()<<' ';cout<<st.pop()<<' ';st.top()=77;st.push(4);st.push(5);st.pop();cout<<st.pop()<<' ';cout<<st.pop()<<endl;cout<<st.pop()<<endl; }catch(const exception& e){cerr<<"EXCEPTION: "<<e.what()<<endl;}}