我想创建一个Matrix结构但是我很难初始化2d数组
1:
struct Matrix{
int r, c;
Matrix(int r, int c){
this->r=r;
this->c=c;
for(int x=0;x<r;x++){
for(int y=0;y<c;y++)
matrix[x][y]=0;
}
}
vector <vector<float>> matrix;
};
2:
struct Matrix{
int r, c;
Matrix(int r, int c){
this->r=r;
this->c=c;
for(int x=0;x<r;x++){
for(int y=0;y<c;y++)
matrix[x][y]=0;
}
}
//int matrix[r][c]; I don't know how to do this
};
我终于得到了一个使用指针的工作
struct Matrix{
float **matrix;
int r, c;
Matrix(int r, int c){
this->r=r;
this->c=c;
matrix = new float*[row];
for(int x=0;x<row;x++){
matrix[x]= new float[c];
for(int y=0;y<col;y++)
matrix[x][y] = 0;
}
}
~Matrix(){
for(int x=0;x<row;x++)
delete[] matrix[x];
delete[] matrix;
cout<<"Matrix deleted"<<endl;
}
};
第三个代码生成的2d数组是否等于普通的2d数组,例如这个?
const int row=10, col=10;
int main(){
float matrix[row][col]={0};
}
在结构中创建一个二维数组是否更好? 并且可以改变使用指针创建的矩阵的值吗?