stack 改进版

来源:互联网 发布:域名管理 新网 编辑:程序博客网 时间:2024/06/09 23:28
<pre name="code" class="cpp">/*   C++ 标准库作者修改版的stack优点1、pop()会返回下一元素2、 如果stack为空,pop()和top()会抛出异常
*/#ifndef STACK_HP#define STACK_HPP#include<deque>#include<exception>using namespace std;template<class T>class Stack{protected:deque<T> c; //container for the elementspublic:class ReadEmptyStack :public exception{public:virtual const char* what() const throw(){return "Read empty stack!";}};typename 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.h"#include<iostream>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;}system("pause");return 0;}

0 0
原创粉丝点击