C++高手帮忙看一下~~急~~~

2024-12-28 19:32:40
推荐回答(1个)
回答1:

错误有好几处,用注释标出了
//匹配括号问题
#include
#include
#include
using namespace std;
//自定义Stack
const float FULL = 0.5;
template
class Stack
{
public:
Stack(int MaxStackSize=10);
~Stack(){delete []stack;}
bool IsEmpty() const {return top==-1;}
bool IsFull() const {return top==MaxTop;}
T Top() const;
Stack& Add(const T&x);
Stack& Delete(T&x);
private:
int top;//栈顶
int MaxTop;//最大的栈顶值
T *stack;//堆栈元素数组
};
template
Stack::Stack(int MaxStackSize)
{//Stack类构造函数
MaxTop=MaxStackSize-1;
stack= new T [MaxStackSize];
top=-1;
}
template
T Stack::Top() const
{//返回栈顶元素
if(IsEmpty()) throw 1;
else return stack[top];
}
template
Stack&Stack::Add(const T&x)
{//添加元素x
if(IsFull()) throw FULL;
stack[++top]=x;
return *this;
}
template
Stack&Stack::Delete(T&x)
{//删除栈顶元素,并将其送入x
if(IsEmpty()) throw 1;
x=stack[top--];
return *this;
}
const int MaxLength=100;//最大字符串长度
void PrintMatchedPairs(char *expr)
{//括号匹配
Stack s(MaxLength);
int j,length=strlen(expr);
//从表达式expr中搜索(和)
for (int i=1;i<=length;i++)
{
if(expr[i-1]=='(') s.Add(i);
else if(expr[i-1]==')')
try{s.Delete(j);cout<
///////////问题出在这
catch (int) //OutOfBounds不是数据类型,用在这里自然出错
{cout<<"No match for right parenthrsis"<<"at"< }
//堆栈中剩下的都是未匹配的
while(!s.IsEmpty())
{
s.Delete(j);
cout<<"No match for left parenthesis at"< }
}//少了}
void main()
{
char expr[MaxLength];
cout<<"Type ab expression of length at most"< cin.getline(expr,MaxLength);
cout<<"The pairs of matching parentheses in"< puts(expr);
cout<<"are"< PrintMatchedPairs(expr); //PrintMatchdPairs(expr)?
}