【发布时间】:2019-03-25 07:33:57
【问题描述】:
我应该如何将 Dynamic Safe 2D 数组类修改为 Dynamic Safe 2D 锯齿状数组类?我读过一篇文章,最好也更安全地使用动态安全或动态安全二维数组,以避免初始化大小小于 0 的数组或大小大于其原始大小的数组。大多数时候,我们会遇到过度递归的问题,比如使用回溯来寻找迷宫的路径。所以我试图实现动态安全的二维锯齿数组类,但我不明白我应该如何实现它?
//Dynamic Safe 2D array class
template <class T>
class DS2DA
{
private:
T **Data;
int nRow;
int nCol;
public:
DS2DA ()
{
nRow=0;
nCol=0;
Data=nullptr;
}
DS2DA (int nRow,int nCol)
{
this->nRow=nRow;
this->nCol=nCol;
Data=new T * [nRow];
for (int i=0;i<nRow;i++)
{
Data[i]=new T [nCol];
}
for (int i=0;i<nRow;i++)
{
for (int j=0;j<nCol;j++)
{
Data[i][j]=0;
}
}
}
T & operator () (int n1,int n2)
{
if ((n1<0 or n1>this->nRow) or (n2<0 or n2>this->nCol))
{
cout<<"Array out of bound";
exit (1);
}
else
return (Data[n1][n2]);
}
};
//Driver Program
int main ()
{
DS2DA <double> obj1 (3,3);
int input;
for (int i=0;i<3;i++)
{
cout<<"Row "<<i+1<<endl;
for (int j=0;j<3;j++)
{
cout<<"Enter Element "<<j+1<<":";
cin>>input;
obj1 (i,j)=input;
}
}
}
【问题讨论】:
-
template<typename T> using DS2DA = std::vector<std::vector<T>>;
标签: c++ class multidimensional-array dynamic jagged-arrays