矢量超出范围

Vector is out of range

本文关键字:范围      更新时间:2023-10-16

祝所有堆垛工度过美好的一天。我正在Quincy2005中运行我的程序,我有以下错误。"在抛出'std::out_of_range的实例后调用Terminate"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);然而,我不知道为什么这条线路会发生这种情况。我希望有人能指导我。

if (ctextLoc > keyvector.size())

应该是

if (ctextLoc >= keyvector.size())

std::vectorsize()返回值1 --- N,其中at()依赖于值0 --- (N - 1)。因此,您应该使用:

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