Note:
1. contains only parentheses () and four arithmetic operations of the +,-, *, And/binary operators.
2. For more general solutions, refer to recursive solutions and expressions tree solutions.
[Cpp]
# Include <cctype>
# Include <map>
# Include <stack>
# Include <string>
# Include <iostream>
Using namespace std;
// A pop-up operator of the operator stack. A pop-up operator of the operand stack is displayed, and the calculation result is
Void Compute (stack <char> & operators, stack <double> & operands)
{
Double op2 = operands. top ();
Operands. pop ();
Double op1 = operands. top ();
Operands. pop ();
Char optr = operators. top ();
Double result;
Switch (optr)
{
Case '+ ':
Result = op1 + op2;
Case '-':
Result = op1-op2;
Case '*':
Result = op1 * op2;
Case '/':
Result = op1/op2;
}
Operands. push (result );
Operators. pop ();
}
// The expression for solving the problem through the operator stack and the operand stack. If the expression is correct, true is returned, and the result is included in the result, false is returned if an error occurs.
Bool ComputeExpr (const string & expr, map <char, int> & priority_tbl, double & result)
{
Stack <double> operands; // operand stack
Stack <char> operators; // operator stack
String inner_expr (expr + '$'); // Add a sentry
Operators. push ('#'); // Sentry
For (int I = 0; I <inner_expr.length (); ++ I)
{
Char ch = inner_expr [I];
If (isdigit (ch) // the operand directly enters the operand Stack
Operands. push (ch-0x30 );
Else // Operator
{
Switch (ch)
{
Case '(':
Operators. push (ch );
Break;
Case ')': // solve the current most internal bracket expression
While (operators. top ()! = '(')
{
If (operators. top () = '#' | operands. size () <2)
Return false;
Compute (operators, operands );
}
Operators. pop ();
Break;
Case '$': // at this time, the correct expression no longer contains parentheses.
While (operators. top ()! = '#')
{
If (operands. size () <2)
Return false;
Compute (operators, operands );
}
If (operands. size () = 1)
{
Result = operands. top ();
Return true;
}
Return false;
Default: // common binary Operators
While (priority_tbl [ch] <= priority_tbl [operators. top ()])
{
If (operands. size () <2)
Return false;
Compute (operators, operands );
}
Operators. push (ch );
}
}
}
}
Int main (int argc, char * argv [])
{
Const string expr_str ("(5 + 6) * 7/(2-9) * 9) + 5 ");
// Priority table. The greater the number, the higher the priority.
Map <char, int> priority_tbl;
Priority_tbl.insert (make_pair ('+', 2 ));
Priority_tbl.insert (make_pair ('-', 2 ));
Priority_tbl.insert (make_pair ('*', 3 ));
Priority_tbl.insert (make_pair ('/', 3 ));
Priority_tbl.insert (make_pair (', 1 ));
Priority_tbl.insert (make_pair ('#', 0 ));
Double result;
Bool ret = ComputeExpr (expr_str, priority_tbl, result );
If (ret)
{
Cout <expr_str <"=" <result <endl;
}
Else
{
Cout <"expression error! "<Endl;
}
Return 0;
}
Author: Challenge_C_PlusPlus