//用末尾的运算符 操作末尾的两个数 voideval(){ int x; auto b = nums.top(); nums.pop(); auto a = nums.top(); nums.pop(); auto c = op.top(); op.pop(); if (c == '+') x = a + b; elseif (c == '-') x = a - b; elseif (c == '*') x = a * b; else x = a / b; nums.push(x); }
//中缀表达式运算顺序 intmain(){ std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); //1.定义哈希表中各个运算符的优先级 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; int j = i; while (j < str.size() && isdigit(str[j])) { /* 将str中连续的数字字符转为int类型 */ x = x * 10 + str[j] - '0'; j++; } i = j - 1; nums.push(x); } elseif (c == '(') { op.push(c); } elseif (c == ')') { while (op.top() != '(') eval();//将栈中所有的运算符从右向左操作一遍 op.pop(); } else { while (op.size() && pr[op.top()] >= pr[c]) eval(); op.push(c); } } while (op.size()) eval();//将所有没有操作完成的运算符从右向左操作一遍 cout << nums.top() << endl; return0; }