堆栈异常:Exception Class Is Not Empty

本文介绍了一种使用C++实现顺序栈的方法,并通过异常处理机制来管理栈溢出和下溢的情况。代码中定义了一个seqstack类,该类利用数组实现栈的基本操作,如push和pop,并通过throw语句抛出异常以处理栈满或栈空的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// stack is sequential list can be inserted or deleted at the top
//seqstack  is a stack using array
#include "stdafx.h"
#include<iostream>
using namespace std;
class pushonfull
{
private:
  int value;
public:
 pushonfull(int item):value(item)
 {}
 int Value()
 {
  return value;
 }
  };
class poponempty
{};
class seqstack
{
private:
 int* data;
 int maxstacksize;
 int top;
public:
 seqstack(int n);
 ~seqstack(void);
 void pushitem(const int item);
 int pop(void);
};
seqstack::seqstack(int n)
{
 data=new int[n];
 maxstacksize=n;
 top=0;
}
seqstack::~seqstack(void)
{
 delete data;
}
void seqstack::pushitem(const int item)
{
 if(top==maxstacksize)
  throw pushonfull(item);
 data[top]=item;
 top++;
}
int  seqstack::pop(void)
{
 if(top==0)
  throw poponempty();
 top--;
 return data[top];
}


int _tmain(int argc, _TCHAR* argv[])
{
 int i;
 seqstack mystack(10);
 try
 {
  for(i=0;i<11;i++)
   mystack.pushitem(i);
 }
 catch(pushonfull obj)
 {
  cout<<"stack is full"<<endl;
  cout<<"the element cannot be inserted is "<<obj.Value()<<endl;
 }
 try
 {
  for(i=0;i<11;i++)
   cout<<mystack.pop()<<" ";
 }
  catch(poponempty)
  {
   cout<<" stack is empty"<<endl;
  }
 
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值