我使用 vector 创建了一个矩阵类< vector > 结构。创建时,矩阵中充满了零(可能不是最好的方法,我打算改变它)。 类的标题是这样的:
class Matrix{
public:
/*Basic constructor, accepts matrix dimensions
Matrix(int nr, int nc);
/*return element i,j*/
double elem(int i, int j);
/*operator () overloading - same thing as previous method*/
double operator()(int i, int j);
private:
vector<vector<double> > Matrix_;
int nr_, nc_;
};
而实现是:
//CONSTRUCTOR
Matrix::Matrix(int nrows, int ncols)
{
nc_ = ncols;
nr_ = nrows;
/*creates rows*/
for (int i = 0; i < nrows; i++)
{
vector<double> row;
Matrix_.push_back(row);
}
/*Fills matrix with zeroes*/
for (int i = 0; i < nr_; i++)
{
for (int j = 0; j < nc_; j++)
{
Matrix_[i].push_back(0);
}
}
}
/*method returning i,j element of the matrix (I overloaded () to do the same)*/
double Matrix::elem(int i, int j)
{
return Matrix_[i][j];
}
/*operator () overloading*/
double Matrix::operator()(int i, int j)
{
return Matrix_[i][j];
}
最后,在我的主程序中:
Matrix m1(rows, cols);
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
m1(i,j) = i*j;
/*OR, using the other method*/
m1.elem(i,j) = i*j;
}
}
问题是我总是返回错误:
matrix.cpp:55:27: error: lvalue required as left operand of assignment
m1.elem(i,j) = i*j;
无论我使用的是方法 .elem() 还是运算符 ()。 所以,我想问题是我没有以正确的方式访问元素来更改它们的值,但我不明白为什么。 任何建议将不胜感激,谢谢!
最佳答案
为了能够修改矩阵元素,您需要返回对它的引用:
double& Matrix::elem(int i, int j) {
return Matrix_[i][j];
}
和:
double& Matrix::operator()(int i, int j) {
return Matrix_[i][j];
}
您还可以为 const
矩阵添加这些:
double Matrix::elem(int i, int j) const {
return Matrix_[i][j];
}
和:
double Matrix::operator()(int i, int j) const {
return Matrix_[i][j];
}
关于c++ - 无法写入矩阵 <vector<vector<double>> 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49960312/