使用vector容器来存储后缀表达式
#include<iostream> #include<stack> #include<string> #include<vector> #include<unordered_map> using namespace std; stack<char> op;//存储运算符 stack<int> num1;//存储数字 vector<string> num;//用来存储后缀表达式 int eval(string s4) { int x, y; x = num1.top(); num1.pop(); y = num1.top(); num1.pop(); if (s4 == "+") return x + y; else if (s4 == "-")return x - y; else if (s4 == "*") return x * y; else if (s4 == "/") return x / y; } int main() { //vector<string> num; unordered_map<char, int> pr{ {'+',1},{'-',1},{'*',2},{'/',2} }; string str; cin >> str; for (int i = 0; i < str.size(); ++i) { auto c = str[i]; if (isdigit(c)) { int x = 0, j = i; while (j < str.size() && isdigit(str[j])) x = x * 10 + str[j++] - '0'; i = j - 1; string s = to_string(x); num.push_back(s); } else if (c == '-' || c == '+' || c == '*' || c == '/') { while (!op.empty() && pr[c] <= pr[op.top()])//若栈顶元素大于等于新的运算符,则出栈 { string s1 = ""; s1 = s1 + op.top(); num.push_back(s1); op.pop(); } op.push(c);//进栈 /*if (op.empty() || pr[c] > pr[op.top()]) { op.push(c); }*/ } else if (c == '(')//左括号直接入栈 { op.push(c); } else if (c == ')')//若是右括号则弹出所有在左括号上面的运算符 { //int j1 = i; while (op.top() != '(') { string s2 = ""; s2 = s2 + op.top(); num.push_back(s2); op.pop(); } op.pop(); } } if (!op.empty())//栈中还存在运算符则移至vector<string> { while (!op.empty()) { string s3 = ""; s3 = s3 + op.top(); num.push_back(s3); op.pop(); } } //后缀表达式计算 for (int k = 0; k<num.size(); k++) { if (num[k].size() > 1)//若是两位以上的数字 { int x1 = 0; for (auto c1 : num[k]) { x1 = x1 * 10 + c1 - '0'; } num1.push(x1); } else //if (num[k] == "-" || num[k] == "+" || num[k] == "*" || num[k] == "/") { for (auto c2 : num[k])//判断是以为数字还是运算符 { if (isdigit(c2))//若是一位数字 { num1.push(c2-'0'); } else { num1.push(eval(num[k])); } break; } //num1.push(eval(num[k])); } } cout << num1.top();//输出结果 return 0; }