我正在制作自己的编程语言(用于学习),但出现错误。
Debug Assertion Failed!
Program: C:/Path/MSVCP140D.dll
Line: 1232
Expression vector subscript out of range
For information how your progr... (Not important)
产生错误的功能:
Parser::Parser(std::vector<std::string> toks) {
for (unsigned i = 0; i < toks.size(); i++) {
if (toks[i++] + " " + toks[i] == "PRINT STRING:") {
std::cout << toks[i += 1] << std::endl;
}
if (toks[i++] + " " + toks[i] == "ASM STRING:") {
std::cout << "FOUND ASM" << std::endl;
}
}
}
产生代币的功能:
Lexer::Lexer(std::string source){
std::string tok = "";
std::string string = "";
int state = 0;
for (int i = 0; i <= source.length(); i++) {
tok += source[i];
if (tok == " ") {
if (state == 1) {
string += tok;
} else tok = "";
} else if (tok == "\n") {
tok = "";
} else if (tok == "print") {
tokens.push_back("PRINT");
tok = "";
} else if (tok == "asm") {
tokens.push_back("ASM");
tok = "";
} else if (tok == "\"") {
if (state == 0) {
state = 1;
} else if (state == 1) {
tokens.push_back("STRING:");
tokens.push_back(string);
string = "";
state = 0;
tok = "";
}
} else if (state == 1) {
string += source[i];
tok = "";
}
}
}
输出:
toks that are generated: PRINTSTRING:print expASMSTRING:ams exp
toks one by one:
PRINT
STRING:
print exp
ASM
STRING:
ams exp
最佳答案
我相信您唯一想增加i
的时间是在这里:
for (unsigned i = 0; i < toks.size(); i++)
// ^^^
循环中先检查
toks[i++]
,然后再检查toks[i]
,结果会非常糟糕。请记住,是toks[i + 1]
不能到达i + 1
吗?与此相同:toks.size()
。也许您应该在循环的主体中包含
toks[i += 1]
,toks[i]
,toks[i + 1]
之类的东西,并且这样:for (unsigned i = 0; i + 2 < toks.size(); i += 3)
另一个问题是:
for (int i = 0; i <= source.length(); i++)
// ^^
// should be <
不知道是不是全部