0

我正在研究一个由二维双精度向量组成的 C++ 类。我即将创建 2D 矢量,但是当我尝试编辑其中的值时,程序崩溃了。我尝试使用 [][] 运算符并将其设置为等于 myDub 并且我尝试使用类似 myMat.editSlot(i,j,myDub) 的类,并且两者都导致程序崩溃。

//n == # of rows and cols (所有矩阵都是正方形) //infile 正确打开文件

mat my_mat(n,n);

// Read input data
for (int i=0; i<n; i++) {
    for (int j=0; j<n; j++) {
        double myDub;
        inFile >> myDub;

        my_mat.editSlot(i,j,myDub);
    }
}

这是课程:

class mat
{

    mat( int x , int y ) {
        int row = x;
        int col = y;
        vector<vector<double>> A( row , vector<double>( row , 0 ) );


        for ( int i = 0; i<row; i++ )
        {
            for ( int j = 0; j<col; j++ )
            {
                cout << setw( 6 ) << A[i][j];
            }
            cout << endl;
        }
    }

    void editSlot( int x , int y , double val ) {
        A[x][y] = val;
    }
    vector<vector<double>> A;

private:
    int n;

};
4

2 回答 2

2

在我看来,您初始化的方式A是错误的。尝试这样的事情:

A = vector<vector<double>>( row , vector<double>( row , 0 ) );

另一个要考虑的构造函数和编辑函数都没有声明为公共的。

于 2017-04-20T05:07:01.290 回答
0

导致崩溃的主要问题是您在构造函数中更改了时间向量 A 的大小,而您在类对象中声明为字段的 A 向量没有被触及。我建议做这样的事情:

mat(int x,int y) : A(y,vector<double>(x,0)) {
 int row = x;
 int col = y;  
    for(int i=0; i<row; i++)
            {
                for(int j=0; j<col; j++)
                {
                    cout<<setw(6)<<A[i][j];
                }
                cout<<endl;
            }
        }
}

在这种情况下,您不会在构造函数中使用临时 A 对象隐藏类中的 A 字段。另外请注意不要在函数中交换 x 和 y。例如,您的 editSlot 函数中有错误:

void editSlot( int x , int y , double val ) {
    A[x][y] = val;
}

, 它应该是:

A[y][x] = val;

根据构造函数。

于 2017-04-20T05:08:53.713 回答