矢量超出范围

时间:2012-07-26 13:34:48

标签: c++ exception vector

所有堆垛机的好日子。 我在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); 但是,我不确定为什么会发生这种情况。 我希望有人能指导我。

2 个答案:

答案 0 :(得分:3)

std::vector的{​​{1}}返回值size(),其中1 --- N依赖于值at()。因此,您应该使用:

0 --- (N - 1)

答案 1 :(得分:3)

if (ctextLoc > keyvector.size())

应该是

if (ctextLoc >= keyvector.size())