#include <iostream>
#include <exception>
#include <deque>
using namespace std;
class Stack
{
private:
deque<int> c;
public:
class ReadEmptyStack : public exception
{
public:
virtual const char *what() const throw()
{
return "read empty stack";
}
};
int size() const
{
return c.size();
}
void push(const int& elem)
{
c.push_back(elem);
}
int pop()
{
if (c.empty())
throw ReadEmptyStack();
int temp = c.back();
c.pop_back();
return temp;
}
int &top()
{
if (c.empty())
throw ReadEmptyStack();
return c.back();
}
};
int main()
{
try{
Stack 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;
}
}
标准程序库中带异常处理的栈实现
最新推荐文章于 2020-08-07 22:39:28 发布