c++计算逆波兰表达式的值
时间: 2023-08-03 10:03:39 浏览: 69
逆波兰表达式求值可以使用栈来实现。具体步骤如下:
1. 初始化一个栈,用于存储操作数和中间结果。
2. 从左到右遍历逆波兰表达式,对于每个元素:
- 如果是数字,入栈。
- 如果是运算符,弹出栈顶的两个元素作为操作数,进行运算,并将运算结果入栈。
3. 最后栈中只剩下一个元素,即为逆波兰表达式的值。
下面是 C++ 代码实现:
```c++
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (auto &s : tokens) {
if (s == "+" || s == "-" || s == "*" || s == "/") {
int b = st.top();
st.pop();
int a = st.top();
st.pop();
if (s == "+") st.push(a + b);
else if (s == "-") st.push(a - b);
else if (s == "*") st.push(a * b);
else if (s == "/") st.push(a / b);
} else {
int num;
stringstream ss(s);
ss >> num;
st.push(num);
}
}
return st.top();
}
int main() {
vector<string> tokens = {"2", "1", "+", "3", "*"};
cout << evalRPN(tokens) << endl; // 9
return 0;
}
```
注意,此代码仅支持整数的四则运算,如果要支持浮点数的运算可以使用 `double` 类型代替 `int`。同时,由于 C++ 没有内置的 split 函数,我们可以使用 stringstream 来实现字符串的分割。