超详细中缀表达式转后缀表达式
2025-09-06 23:46:35
发布于:上海
可用于自制编程语言
起因是我有个朋友叫张嘉#
我就联想到了张++
于是有了zhaj语言
(zhang jia ### -> zha j)
so 为了处理这些,我(其实是deepseek+人工改代码)自己去做了一个中缀表达式转后缀表达式
废话不多说,亮代码!
(应为我这是在项目里,不知道那个头文件是项目里的,所以都写下来了)
#include <iostream>
#include <string>
#include <cmath>
#include <windows.h>
#include <fstream>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <cctype>
#include <cstdlib>
#include <stack>
#include <unordered_set>
using namespace std;
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
// 中缀转后缀(支持函数如abs)
// ... 保留原有头文件和宏定义 ...
// 预定义的函数名列表
unordered_set<string> predefinedFunctions = { "sin", "cos", "log", "cosh", "sinh", "tan", "abs" };
// 判断是否是函数名
bool isFunction(const string& token) {
return predefinedFunctions.count(token);
}
// 修改后的优先级函数
int precedence(const string& op) {
if (isFunction(op)) return 5; // 函数优先级最高
if (op == "^") return 4;
else if (op == "*" || op == "/") return 3;
else if (op == "+" || op == "-") return 2;
return 0;
}
// 修改后的中缀转后缀函数
string infixToPostfix(string infix) {
stack<string> operatorStack;
string output;
for (int i = 0; i < infix.size(); i++) {
if (infix[i] == ',') {
infix[i] = ' ';
}
}
for (int i = 0; i < infix.size();) {
char c = infix[i];
// 跳过空格
if (c == ' ') {
i++;
continue;
}
// 处理数字
if (isdigit(c) || c == '.') {
while (i < infix.size() && (isdigit(infix[i]) || infix[i] == '.')) {
output += infix[i++];
}
output += ' ';
continue;
}
// 处理字母序列(函数或变量)
if (isalpha(c)) {
string token;
while (i < infix.size() && isalpha(infix[i])) {
token += infix[i++];
}
// 检查后面是否有左括号,判断是否是函数调用
if (i < infix.size() && infix[i] == '(' && isFunction(token)) {
operatorStack.push(token);
operatorStack.push("("); // 压入左括号
i++; // 跳过'('
}
else {
// 变量直接输出
output += token + ' ';
}
continue;
}
// 处理左括号
if (c == '(') {
operatorStack.push(string(1, c));
i++;
}
// 处理右括号
else if (c == ')') {
while (!operatorStack.empty() && operatorStack.top() != "(") {
output += operatorStack.top() + ' ';
operatorStack.pop();
}
operatorStack.pop(); // 弹出左括号
// 检查是否有函数名
if (!operatorStack.empty() && isFunction(operatorStack.top())) {
output += operatorStack.top() + ' ';
operatorStack.pop();
}
i++;
}
// 处理普通操作符
else if (isOperator(c)) {
string currentOp(1, c);
bool isRightAssociative = (currentOp == "^");
while (!operatorStack.empty() &&
((!isRightAssociative && precedence(currentOp) <= precedence(operatorStack.top())) ||
(isRightAssociative && precedence(currentOp) < precedence(operatorStack.top())))) {
output += operatorStack.top() + ' ';
operatorStack.pop();
}
operatorStack.push(currentOp);
i++;
}
}
// 弹出剩余操作符
while (!operatorStack.empty()) {
output += operatorStack.top() + ' ';
operatorStack.pop();
}
return output;
}
这里空空如也
有帮助,赞一个