C++ 测试C++;中缀堆栈的后缀
我目前正在尝试测试是否有太多的操作数,但无法确定后缀表达式有太多操作数的条件 有人能给我一些关于测试什么的建议吗 以下是我目前的功能:C++ 测试C++;中缀堆栈的后缀,c++,algorithm,stack,postfix-notation,infix-notation,C++,Algorithm,Stack,Postfix Notation,Infix Notation,我目前正在尝试测试是否有太多的操作数,但无法确定后缀表达式有太多操作数的条件 有人能给我一些关于测试什么的建议吗 以下是我目前的功能: void evaluatePostFix(string str){ Stack stack; // Strip whitespaces str.erase(str.find(' '), 1); if (str.length() == 1 || str.length() == 0){ string singleOpe
void evaluatePostFix(string str){
Stack stack;
// Strip whitespaces
str.erase(str.find(' '), 1);
if (str.length() == 1 || str.length() == 0){
string singleOperand;
singleOperand.push_back(str[0]);
stack.push(createExpression("", singleOperand, ""));
}
int count = 0;
for (const char & c : str){
count++;
if (isOperand(c)){
string singleOperand;
singleOperand.push_back(c);
stack.push(singleOperand);
} else {
if (stack.isEmpty()){
cout << "To many operators" << endl;
return;
}
string operand1 = stack.top();
stack.pop();
if (stack.isEmpty()){
cout << "To many operators" << endl;
return;
}
string operand2 = stack.top();
stack.pop();
string operator1, expression;
operator1.push_back(c);
expression = createExpression(operand1, operand2, operator1);
stack.push(expression);
}
}
stack.print();
}
void evaluatePostFix(字符串str){
堆叠;
//带空白
str.erase(str.find(“”),1);
如果(str.length()==1 | | str.length()==0){
字符串单操作数;
单操作数。push_back(str[0]);
push(createExpression(“,singleOperand,”);
}
整数计数=0;
for(常量字符和c:str){
计数++;
if(等规数(c)){
字符串单操作数;
单操作数。推回(c);
stack.push(单操作数);
}否则{
if(stack.isEmpty()){
cout我认为您考虑得太多了。要评估后缀符号,请执行以下操作:
堆砌
迭代输入
如果找到一个操作数,请将其推到堆栈上
如果发现某个操作,请弹出执行该操作所需的操作数。应用该操作,然后将结果推回堆栈。如果无法弹出正确的操作数,则表示操作数太少
在这个过程结束时,堆栈中应该剩下一个项——结果。如果有多个项,那么在某个点上操作数过多
下面是一个可读的python实现来说明:
def evaluate_postfix(inputstr):
# split into a list of parts consisting of operands and operators
ops = inputstr.split()
stack = []
for i in ops:
# if it's an operand push to the stack
if i.isdigit():
stack.append(int(i))
else:
# if there's not enough operands exit
if len(stack) < 2:
print("TOO FEW OPERANDS")
exit()
else:
# pop the operands, apply the operation, and push the result
a, b = stack.pop(), stack.pop()
if i == '+': stack.append(a + b)
elif i == '-': stack.append(a - b)
elif i == '/': stack.append(a / b)
else: stack.append(a * b)
# if there are multiple values left in the stack then at some point
# there were too many operands for the number of operations
if len(stack) != 1:
print("TOO MANY OPERANDS")
exit()
return stack[0]
感谢您的阅读,尽管它确实说明了如何捕捉异常!这完全是过虑了。很高兴能提供帮助:)
print(evaluate_postfix("1 2 + 3 *"))
# 9
print(evaluate_postfix("1 2 + 3 * *"))
# TOO FEW OPERANDS
print(evaluate_postfix("1 2 3 4 + +"))
# TOO MANY OPERANDS