c++ Vector subscript out of range error

时间:2021-04-25 16:40:03

The program is supposed to open a .csv file and input the data into a vector. Later I'm supposed to implement a priority queue. However I'm getting this error when I try to run it.

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

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "*er.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("*er_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 << "  ";
}
*er p[100]; // Initializing *er 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;

}

}

I can also include the *er class if needed to figure out the issue.

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

1 个解决方案

#1


2  

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

should be

应该

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

#1


2  

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

should be

应该

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