向量下标超出范围错误

时间:2013-10-08 14:14:46

标签: c++ vector stl

我有一些代码来比较不同人回答的问题集,一组用户输入其他集来自.txt文件。当我运行它时,它给我一个超出范围的断言错误向量下标,我无法找到它来自哪里。这是代码:

 void compare()
{
    const int qnum = 11;
    string filename, temp;
    string search[10] = {"1","2","3","4","5","6","7","8","9","0"};
    int answers[qnum], i, j, k, q= 0, numtemp = 0, pplNum;
    ifstream infile;
    vector <string> people;
    vector <int> pplans;
    vector <int> pplscore;

    cout << "Please enter the name of the file you would like to enter: ";
    cin >> filename;

    string infilename= filename;
    infile.open(infilename.c_str());

    //Temporary test part of the program until we add the GUI just copy another person's answer or put similar ones
    //for testing purposes


    infile >> pplNum;
    //allows for all names and scores to fit in each vector
    for(i = 0; i < pplNum; i++)
    {
        people.push_back("");
        people.push_back("");
        pplscore.push_back(0);
    }
    //takes the person's name
            for(j = 0; !infile.eof(); j+ 2)
        {
            infile >> people[j];
            infile >> people[j+1];
        }

        for(i = 0; i < pplNum; i++)
        {
            //sets the numbers for the individual in question
            for(k = 0; k < qnum; k++)
            {
                infile >> pplans[k];
                if(answers[k] == pplans[k] && k < 10)
                    numtemp++;
                else if (k == 10 && answers[k] == pplans[k])
                    if(answers[answers[k]] == pplans[pplans[k]])
                        numtemp++;
            }
            pplscore.push_back(0);
            pplscore[i] = numtemp;

        }
}   

1 个答案:

答案 0 :(得分:0)

vector <int> pplans;
...
infile >> pplNum;
//allows for all names and scores to fit in each vector
for(i = 0; i < pplNum; i++)
{
  people.push_back("");
  people.push_back("");
  pplscore.push_back(0);
}
...
for(i = 0; i < pplNum; i++)
{
  //sets the numbers for the individual in question
  for(k = 0; k < qnum; k++)
  {
    infile >> pplans[k];
    ...
  }
}

你忘了在pplans腾出空间。 (并且最好将push_back与实际数据一起使用,而不是依赖于这样的代码。)