2016-02-17 143 views
1

我正在編寫自己的編程語言(用於學習),我有錯誤。矢量下標超出範圍?

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

功能產生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 = ""; 
     } 
    } 
} 

輸出:

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

回答

2

我相信你想增加i唯一的一次在這裏:

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

toks[i++],然後在沒有勾選Loop toks[i]會變成很糟糕。應該是toks[i + 1],請記住i + 1不能達到toks.size()?同樣的:toks[i += 1]

也許你應該有這樣的東西toks[i]toks[i + 1]toks[i + 2]在循環的身體,這樣的:

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

而另一個問題是:

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

我不知道這是所有。

+0

我改變它,仍然是一樣的:/ – pyDzoni

+0

@pyDzoni沒有MCVE,我不能幫你。這是我所能看到的。坦率地說,你好運,這還沒有結束,你有這個部分答案。 – LogicStuff

+0

對不起,我沒有看到我+ 2 – pyDzoni