2012-07-26 100 views
-2

所有堆垛機的好日子。 我正在Quincy2005上運行我的程序,並且出現以下錯誤。 「扔「的std :: out_of_range實例終止後,被稱爲」 「是什麼():向量:: _ M_range_check」向量超出範圍

下面是我的一堆代碼

int ptextLoc,ctextLoc;  //location of the plain/cipher txt 
char ctextChar;  //cipher text variable 
//by default, the location of the plain text is even 
bool evenNumberLocBool = true; 
ifstream ptextFile; 
//open plain text file 
ptextFile.open("ptext.txt"); 

    //character by character encryption 
    while (!ptextFile.eof()) 
    { 

     //get (next) character from file and store it in a variable ptextChar 
     char ptextChar = ptextFile.get(); 

     //find the position of the ptextChar in keyvector Vector 
     ptextLoc = std::find(keyvector.begin(), keyvector.end(), ptextChar) - keyvector.begin(); 

     //if the location of the plain text is even 
     if ( ((ptextLoc % 2) == 0) || (ptextLoc == 0)) 
      evenNumberLocBool = true; 
     else 
      evenNumberLocBool = false; 

     //if the location of the plain text is even/odd, find the location of the cipher text  
     if (evenNumberLocBool) 
      ctextLoc = ptextLoc + 1; 
     else 
      ctextLoc = ptextLoc - 1; 


     //store the cipher pair in ctextChar variable 
     ctextChar = keyvector.at(ctextLoc); 

     cout << ctextChar; 

    } 

ptext.txt 內容ab cd ef

如果第一個字母是位於位置0的'a',則密碼字母對將是kevector [1]。

最新更新:我發現已經創建此錯誤的行。 ctextChar = keyvector.at(ctextLoc); 但是,我不確定爲什麼會發生這一行。 我希望有人能夠引導我。

回答

3

std::vectorsize()返回一個值1 --- N,其中作爲at()依賴於值0 --- (N - 1)。因此,你應該使用:

if (keyvector.size() != 0 && ctextLoc > keyvector.size() - 1) 
    break; 
+1

'的push_back()''返回void'。我也不這麼認爲,這行是爲了存儲在矢量中,但是從矢量中讀取數據,所以它應該沒問題。 – Nobody 2012-07-26 13:39:29

+0

@我沒有人重讀過它,並相應地進行了更正。 – Drise 2012-07-26 13:41:08

+0

還有一個小缺陷:當vector爲空時'size()'可以返回0。如果向量不是空的,則應該簡單地區分大小和最後一個有效索引,後者爲size() - 1。 – Nobody 2012-07-26 13:43:24

3
if (ctextLoc > keyvector.size()) 

大概應該是

if (ctextLoc >= keyvector.size())