用位矩阵加载向量



这里有一个代码段,它将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 zeron" );  // 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]

有人知道为什么会这样吗?

在第二个for循环中的Write()函数中,您正在增加count而不是count2:

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

下一行然后调用分段错误,因为您正在访问矩阵中的值越界。

最新更新