优化代码:#include iostream#include string#include mapusing namespace std;class PythonInterpreter private mapstring bool boolVariables; mapstring int intVariables; mapstring float floatVariables;
优化代码:
- 使用unordered_map代替map,因为unordered_map的查找效率更高。
- 将bool、int、float、string变量的存储合并到一个unordered_map中,使用variant来存储不同类型的值。
- 使用正则表达式来解析代码行,提取变量名和值,可以更方便地处理不同的情况。
- 简化输出变量内容的逻辑,使用variant的visit方法来处理不同类型的值。
- 将代码解析和执行分离,使得代码更加清晰和易于扩展。
#include
using namespace std;
class PythonInterpreter { private: unordered_map<string, variant<bool, int, float, string>> variables;
public:
void execute(string filename) {
string code = readFile(filename);
vector
for (const string& line : lines) {
parseLine(line);
}
}
private: string readFile(string filename) { // 读取文件内容并返回 // 实现略 }
vector<string> splitCode(string code) {
vector<string> lines;
size_t pos = 0;
while ((pos = code.find("\n")) != string::npos) {
string line = code.substr(0, pos);
code.erase(0, pos + 1);
lines.push_back(line);
}
lines.push_back(code);
return lines;
}
void parseLine(string line) {
if (line.empty()) return;
regex pattern(" *(\\w+) *= *(.+)");
smatch matches;
if (regex_match(line, matches, pattern)) {
string varName = matches[1];
string value = matches[2];
if (value.find("\"") == 0) {
// 字符串类型
string strValue = value.substr(1, value.size() - 2);
variables[varName] = strValue;
} else if (value == "True") {
// 布尔类型
variables[varName] = true;
} else if (value == "False") {
// 布尔类型
variables[varName] = false;
} else if (value.find(".") != string::npos) {
// 浮点数类型
float floatValue = stof(value);
variables[varName] = floatValue;
} else {
// 整数类型
int intValue = stoi(value);
variables[varName] = intValue;
}
} else if (line.find("print(") == 0) {
// 输出变量内容
string varName = line.substr(6, line.size() - 7);
if (variables.find(varName) != variables.end()) {
variant<bool, int, float, string> value = variables[varName];
visit([](const auto& v){ cout << v << endl; }, value);
}
}
}
};
int main() { PythonInterpreter interpreter; interpreter.execute("test.uil");
return 0;
}
原文地址: https://www.cveoy.top/t/topic/i2Dq 著作权归作者所有。请勿转载和采集!