顺序反了就错了
运行下面这段程序——注意减法两个数的先后:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int calc(const vector<string>& tokens) {
vector<int> st;
for (const string& t : tokens) {
if (t == "+" || t == "-" || t == "*") {
int b = st.back(); st.pop_back();
int a = st.back(); st.pop_back();
if (t == "+") st.push_back(a + b);
else if (t == "-") st.push_back(a - b);
else st.push_back(a * b);
} else {
st.push_back(stoi(t));
}
}
return st.back();
}
int main() {
cout << calc({"5", "1", "-"}) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论