简体   繁体   中英

Out of range vector subscript C++

I have this method in one of my cpp files where I have navigated my failure to be. I have also added cout statements and checked that there is content in both foo and mainWord. I think my problem has to do with how I've added elements to foo or how I am trying to re-add them. The size mainWord is 88 and the size of foo is more than 1000. Here is where I add elements to foo:

while (myfile>>magic)//store the colours in an array
{
     foo.push_back(magic);
}

and here is where I try and change them and add them back in.

void Penguin::addWord(std::vector<int> foo)
 {
 unsigned fooCounter=0;
 int temp;
for (int i=0;i<88;i+2)
 {
     if(foo.at(fooCounter) == 11111111 && foo.at(fooCounter) != NULL)
     {
         if(mainWord[i]==1 && mainWord[i+1]==1)
         {
             foo.at(fooCounter) = 11111111;
         }
         else if(mainWord[i]== 1 && mainWord[i+1] == 0)
         {
                 foo.at(fooCounter) = 11111110;
         }
         else if(mainWord[i]== 0 && mainWord[i+1] == 1)
         {
             foo.at(fooCounter) = 11111101;
         }
         else
        {
                 foo.at(fooCounter) = 11111100;
        }
     }
     else if (foo.at(fooCounter) == 11111111 && foo.at(fooCounter) != NULL)
     {
         if(mainWord[i]== 1 && mainWord[i+1] == 1)
         {
             foo.at(fooCounter) = 00000011;
         }
         else if(mainWord[i]== 1 && mainWord[i+1] == 0)
         {
             foo.at(fooCounter) = 00000010;
         }
         else if(mainWord[i]== 0 && mainWord[i+1] == 1)
         {
             foo.at(fooCounter) = 00000001;
         }
         else
        {
            foo.at(fooCounter) = 00000000;
         }
     }
     fooCounter++;
 }

}

I keep getting an error that says: "Debug Assertion Failed. Vector subscript out of range" ...Please help

You have an infinite loop because i is never updated in the for loop. You need to fix the typo:

for (int i=0;i<88;i+=2)
                    ^
                    ^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM