Segmentation fault on two dimensional vector

2019-09-14 07:09发布

问题:

I have a file that contains values in a table format. The number of rows and columns in the file may vary.

33829731.00 -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00
205282038.00    -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00
3021548.00  -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00
203294496.00    -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00
205420417.00    -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00   -1.00

I am using a two dimensional vector to store the data using the following code.

ifstream inputCent("file.txt");

std::vector<std::vector<double> > C;
std::vector<double> col(15);

while(!inputCent.eof())
{
    for(int i = 0; i < col.size(); i++)
    {
        inputCent >> col[i];
        C[i].push_back(col[i]);
    }
}

But this is giving me Segmentation fault: 11. However if I initialize std::vector<std::vector<double> > C(15); like this then it works for 15 rows. But as I said the number of rows may vary. Why do I have to initialize the size of C? Or what am I doing wrong?

回答1:

You're trying to push_back to a vector that may not exist... The correct code is below:

ifstream inputCent("file.txt");

std::vector<std::vector<double> > C;
std::vector<double> col(15);

while(!inputCent.eof())
{
    for(int i = 0; i < col.size(); i++)
    {
        inputCent >> col[i];  
    }
    C.push_back(col);
}

As shown above, it makes more sense to populate your col vector with values before pushing the entire col vector to the back of C.