用位矩阵加载向量

Posted

技术标签:

【中文标题】用位矩阵加载向量【英文标题】:Loading vector with bit matrix 【发布时间】:2016-10-11 04:12:07 【问题描述】:

我在这里有一个代码段,它将零加载到表示位矩阵的向量中。当程序运行并尝试将结果写入输出文件时,我得到一个段错误。程序在不写入输出文件时运行良好。

[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]

谁能明白为什么会这样?

【问题讨论】:

【参考方案1】:

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

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

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

【讨论】:

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

以上是关于用位矩阵加载向量的主要内容,如果未能解决你的问题,请参考以下文章

犰狳中的矩阵(向量)在从文件加载后获得新的小数位

c++中的二维向量问题

使用intel内在函数加载内存中等距的双精度数?

将 NEON 组件与非向量函数混合

通过指针、强制转换和取消引用加载向量?

从 Assimp 加载 Collada (dae) 模型显示不正确的法线