1#include <iostream>2#include <string>3 using namespacestd;4 5Template<typename t>6 classStack7 {8 Private:9T stack[ -];Ten inti =0; One Public: AStack () =default; - - T pop () the { - if(i = =-1) - { -cout <<"stack is empty! "<<Endl; + return 0; - } + AT top = stack[i-1]; at--i; - returntop; - } - - voidpush (T num) - { in++i; -Stack[i-1] =num; to } + - voidClear () the { * for(intj =0; J < -; ++j) $ {Panax NotoginsengT[J] =0; - } the } + }; A the intMain () + { -stack<string>ops; $stack<Double>num; $ stringstr; - -Std::cout <<"Please enter a formula:"<<Endl; thecout <<"Note: Each character putting, please separate the sub-expression, please enclose in parentheses"<<Endl; -cout <<"The character E represents the end"<<Endl;Wuyi while(true) the { -CIN >>str; Wu if(str = ="(")Continue; - Else if(str = ="+") Ops.push (str); About Else if(str = ="-") Ops.push (str); $ Else if(str = ="*") Ops.push (str); - Else if(str = ="/") Ops.push (str); - Else if(str = =")") - { A stringOP =Ops.pop (); + Doubleval =Num.pop (); the if(OP = ="+") val = num.pop () +Val; - if(OP = ="-") val = Num.pop ()-Val; $ if(OP = ="*") val = Num.pop () *Val; the if(OP = ="/") val = Num.pop ()/Val; the Num.push (val); the } the - Else if(str! ="E") in { the Doubleval =Stod (str); the Num.push (val); About } the the if(str = ="E") the { + Break; - } the }Bayi thecout <<"The result is:"; thecout << Num.pop () <<Endl; - - return 0; the}View Code
Dijkstra binary arithmetic expression evaluation algorithm C + + implementation