【问题标题】:Segmentation fault on two dimensional vector二维向量上的分割错误
【发布时间】:2017-03-01 15:47:48
【问题描述】:

我有一个包含表格格式值的文件。文件中的行数和列数可能会有所不同。

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

我正在使用二维向量来存储数据,使用以下代码。

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]);
    }
}

但这给了我Segmentation fault: 11。但是,如果我像这样初始化std::vector&lt;std::vector&lt;double&gt; &gt; C(15);,那么它适用于 15 行。但正如我所说,行数可能会有所不同。为什么一定要初始化C的大小?或者我做错了什么?

【问题讨论】:

    标签: c++11 vector segmentation-fault


    【解决方案1】:

    您正在尝试push_back 到一个可能不存在的向量...正确的代码如下:

    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);
    }
    

    如上所示,在将整个 col 向量推到C 后面之前,用值填充col 向量更有意义。

    【讨论】:

    • 知道了,谢谢。 :) 愚蠢的错误。
    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多