2016-10-11 29 views
0

我有一个代码段,它将零加载到表示位矩阵的向量中。当程序运行并尝试将结果写入输出文件时,我会遇到seg错误。当程序没有写入输出文件时,程序运行正常。用位矩阵加载向量

[code] 
Bitmatrix::Bitmatrix(int rows, int cols) 
{ 
    int count = 0;                   // count variable 
    int count2 = 0;                  // 2nd count variable 

    if(rows <= 0 || cols <= 0) 
    { 
     fprintf(stderr, "Value of rows or columns is less than or equal to zero\n"); // print error message 
     M.resize(1);                 // resize to 1 x 1 matrix 
     M[0] = '0';                 // set 0 as the value 
    } 
    else 
     M.resize(rows);               // resize matrix to number of rows 
     for(count = 0; count < M.size(); count++) 
     { 
      for(count2 = 0; count2 < cols; count2++) 
      { 
       M[count].push_back('0');          // fill matrix with zeros 
      } 
     } 
}[/code] 

,在输出文件打印功能是:

[code]void Bitmatrix::Write(string fn) 
{ 
    ofstream out;              // output stream object 
    int count = 0;             // count variable 
    int count2 = 0;             // 2nd count variable 

    out.open(fn.c_str());          // open output file 
    for(count = 0; count < M.size(); count++) 
    { 
     for(count2 = 0; count2 < M[count].size(); count++) 
     { 
      out << M[count][count2]; 
     } 
     out << endl; 
    } 
}[/code] 

有人能看到为什么会这样?

回答

0

在你的第二个for循环功能Write()你递增count,而不是count2

for(count2 = 0; count2 < M[count].size(); count++ <= should be count2 

下一行然后调用分段错误,因为你正在访问的是出了矩阵的值界限。

+0

谢谢。我总是忽略这样的事情。 – miamidawgs

+0

如果我的答案对您有帮助,请将其标记为已接受。 –