c ++向量下标超出范围错误

时间:2015-10-24 00:47:55

标签: c++ vector

程序应该打开.csv文件并将数据输入到矢量中。后来我应该实现一个优先级队列。但是当我尝试运行它时,我收到了这个错误。

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "Prisoner.h"
#include "Jailed.h"
using namespace std;

int main()
{

string line, ID, sentenceIn, servedIn, lastName, firstName;
int sentence, served;

vector<string> idNum;
vector<int> sentenceLen;
vector<int> servedTime;
vector<string> lastNameIn;
vector<string> firstNameIn;


ifstream data("prisoner_data.csv");

if (!data.is_open())
{
    exit(EXIT_FAILURE);
}

while (getline(data, line))
{

    getline(data, ID, ',');
    cout << ID << "  ";
    idNum.push_back(ID);

    getline(data, sentenceIn, ',');
    cout << sentenceIn << "  ";
    istringstream(sentenceIn) >> sentence;
    sentenceLen.push_back(sentence);


    getline(data, servedIn, ',');
    cout << servedIn << "  ";
    istringstream(servedIn) >> served;
    servedTime.push_back(served);


    getline(data, lastName, ',');
    lastNameIn.push_back(lastName);
    cout << lastName << "  ";

    getline(data, firstName, ',');
    firstNameIn.push_back(firstName);
    cout << firstName << "  ";
}
Prisoner p[100]; // Initializing Prisoner class

for (int i = 0; i <= idNum.size(); i++)
{
    p[i].setIdNum(idNum[i]);
    p[i].setSentence(sentenceLen[i]);
    p[i].setTimeServed(servedTime[i]);
    p[i].setLastName(lastNameIn[i]);
    p[i].setFirstName(firstNameIn[i]);
}

data.close();
system("pause");
return 0;

}

如果需要,我还可以包括囚犯班来解决问题。

1 个答案:

答案 0 :(得分:2)

NumberFormat

应该是

for (int i = 0; i <= idNum.size(); i++)