-2

所有堆垛机的美好一天。我在 Quincy2005 中运行我的程序,并且出现以下错误。“抛出 'std::out_of_range 的实例后调用终止” “what(): vector::_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); 但是,我不确定为什么这条线会发生这种情况。我希望有人能够指导我。

4

2 回答 2

3

std::vector'ssize()返回一个值1 --- N,其中 asat()依赖于值0 --- (N - 1)。因此,您应该使用:

if (keyvector.size() != 0 && ctextLoc > keyvector.size() - 1)
  break;  
于 2012-07-26T13:37:08.733 回答
3
if (ctextLoc > keyvector.size())

应该是

if (ctextLoc >= keyvector.size())
于 2012-07-26T13:38:20.203 回答