简体   繁体   English

向量下标超出范围?

[英]Vector subscript out of range?

I am making my own programming language (for learning) and I have error. 我正在制作自己的编程语言(用于学习),但出现错误。

Debug Assertion Failed!
Program: C:/Path/MSVCP140D.dll
Line: 1232

Expression vector subscript out of range

For information how your progr... (Not important)

function that make error: 产生错误的功能:

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;
        }
    }
}

function that generate toks: 产生代币的功能:

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 = "";
        }
    }
}

Output: 输出:

toks that are generated: PRINTSTRING:print  expASMSTRING:ams  exp
toks one by one:
PRINT
STRING:
print exp
ASM
STRING:
ams exp

I believe the only time you want to increment i is here: 我相信您唯一想增加i是在这里:

for (unsigned i = 0; i < toks.size(); i++)
//                                    ^^^

toks[i++] and then toks[i] in the loop without a check will turn out very bad. toks[i++] ,然后在没有检查的情况下在循环中执行toks[i] ,结果将非常糟糕。 Should it be toks[i + 1] , keeping in mind i + 1 can't reach toks.size() ? 应该是toks[i + 1] ,请记住i + 1无法到达toks.size()吗? Same for this: toks[i += 1] . 与此相同: toks[i += 1]

Maybe you should have stuff like toks[i] , toks[i + 1] , toks[i + 2] in the body of the loop and this: 也许您应该在循环的主体中包含toks[i]toks[i + 1]toks[i + 2]之类的东西:

for (unsigned i = 0; i + 2 < toks.size(); i += 3)

And another problem is: 另一个问题是:

for (int i = 0; i <= source.length(); i++)
//                ^^
//           should be <

I don't know if that's all. 不知道是不是全部

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM