C++ 使用唯一指针动态分配矩阵
我试图解决的练习表明,我应该使用允许以下操作的唯一指针创建一个动态分配的矩阵: 矩阵a,b; 矩阵cb; 矩阵d=a; 矩阵e=a+b; 到目前为止,我已经尝试实现了不包括加法的矩阵,但是我无法理解在这个示例中应该如何实现唯一指针C++ 使用唯一指针动态分配矩阵,c++,matrix,unique-ptr,C++,Matrix,Unique Ptr,我试图解决的练习表明,我应该使用允许以下操作的唯一指针创建一个动态分配的矩阵: 矩阵a,b; 矩阵cb; 矩阵d=a; 矩阵e=a+b; 到目前为止,我已经尝试实现了不包括加法的矩阵,但是我无法理解在这个示例中应该如何实现唯一指针 class Matrix { public: vector<vector<int>> data; Matrix() {} Matrix(vector<vector<int>> matrix
class Matrix
{
public:
vector<vector<int>> data;
Matrix() {}
Matrix(vector<vector<int>> matrix)
{
this->data=matrix;
}
Matrix (const Matrix& m2)
{
this->data=m2.data;
}
Matrix& operator= (const Matrix &m2)
{
this->data = m2.data;
return *this;
}
void print()
{
vector< vector<int> >::iterator row;
vector<int>::iterator col;
for (row = data.begin(); row != data.end(); row++)
{
for (col = row->begin(); col != row->end(); col++)
{
cout<<*col<<" ";
}
cout<<endl;
}
}
} ;
int main()
{
vector<vector<int> > matrix(3);
for ( int i = 0 ; i < 3 ; i++ )
matrix[i].resize(3);
Matrix m(matrix);
m.print();
Matrix m2(m);
m2.print();
Matrix m3;
m3=m2;
m3.print();
}
非常感谢你的帮助。干杯。解决方案的唯一实际问题是使用向量向量,这可能会有点低效,因为在访问内部向量时存在额外的间接级别 最好是分配一个向量来存储整个矩阵,因此:
class Matrix
{
public:
vector<int> data;
int width;
Matrix(int w, int h) : data (w * h), width(w)
{
}
int& elementAt(int x, int y)
{
// Offset the row with y * width, then in the row the xth element
return data[y * width + x];
}
...
但我想知道问题的关键是什么。我看不出有任何明显的效率差异。两者都会自动释放内存
从功能上讲,你已经有了一个额外的步骤,必须将数据归零。当然,你可能不想这样做。此外,您还没有数据的总大小。向量存储其自身的大小,但数组不存储,因此您可能需要单独存储高度和宽度
加向量通常更容易编程。方阵?对于大小为n的矩阵,只需分配n*n个整数并将其存储在唯一的\u ptr中。即,数据=标准::使唯一*n;。您还必须存储大小,size=n。在你的主构造函数中,实现所有其他的操作。我不知道你的意思。是否要将数据存储在唯一的\u ptr中?如果是,为什么?向量似乎更适合。或者您想为矩阵创建唯一的\u ptr,例如std::unique\u ptr?如果是,请向我们展示一个您尝试了什么和失败了什么的示例。您的赋值指定了唯一的指针,但您使用的是向量。这很可能不是你的导师想要的。我只是错误地证明了向量解是多么安全;
class Matrix
{
public:
unique_ptr<int[]> data;
int width;
Matrix(int w, int h)
: data (new int[w * h]), width(w) // Allocate dynamic array in unique_ptr
{
// Initialize data to zero
}
int& elementAt(int x, int y)
{
// Offset the row with y * width, then in the row the xth element
return data[y * width + x];
}
...