在一个变量中存储多个 2D 数组

Store multiple 2d arrays in a variable

本文关键字:存储 2D 数组 一个 变量      更新时间:2023-10-16

我正在生成一个nxn对角矩阵,例如,如果n=3生成的矩阵将是

1 0 0
0 1 0
0 0 1

然后我将矩阵旋转n-1次,例如在上述情况下是2

0 0 1
1 0 0
0 1 0
0 1 0
0 0 1
1 0 0

我需要自动生成n-1变量。将旋转矩阵存储在变量中。打印变量名和存储在其中的矩阵,例如输出应该是这样的

a1
0 0 1
1 0 0
0 1 0
a2
0 1 0
0 0 1
1 0 0

有没有办法自动生成变量?我正在使用c ++,并且正在学习它。

更新

我使用你说的逻辑将这些旋转矩阵存储在变量中。现在我已经将这些矩阵对角线打印在mxm对角矩阵中,m=n*n例如在我的情况下n=3如此m=9。输出看起来像

1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 0 0

但是我需要输出应该看起来像

1 0 0  0 0 0  0 0 0
0 1 0  0 0 0  0 0 0
0 0 1  0 0 0  0 0 0
0 0 0  0 0 1  0 0 0
0 0 0  1 0 0  0 0 0
0 0 0  0 1 0  0 0 0
0 0 0  0 0 0  0 1 0
0 0 0  0 0 0  0 0 1
0 0 0  0 0 0  1 0 0

我被困在 for 循环中。

矩阵

通常使用向量C++实现:

vector< vector<int> > myTwoDArray; // this will create an empty maxtrix

要以一定的大小初始化它,您可以执行以下操作:

vector< vector<int> > myTwoDArray(n, vector<int>(n)); 
//this will create a n*n 2D array in which every element is 0

然后要修改元素,您可以使用 [] 运算符,例如

myTwoDArray[1][2] = 1; // row 1 col 2 is now 1(if we start counting from 0)

更新

要将 2D 矩阵的数量存储在 n 个变量中,将它们存储在向量中可能更易于组织。也就是说,我们可以简单地应用相同的逻辑来创建 2D 矩阵的向量(或者我们可以将其视为 3D 数组(

vector< vector< vector<int> > > store(n,  vector< vector<int> >(n, vector<int>(n))); 

例如,如果n=3,则store[0]store[1]store[2]将分别保存一个 3*3 矩阵。要更改每个"变量"的矩阵元素,您可以简单地:

store[0][1][2] = 2; //change row 1, col 2 of the matrix in variable 0 to 2

初始化矩阵的另一个非常好且更简单的方法是使用 C++11 初始化列表(确保您的编译器支持 C++11(:

store[0] = { {0,0,1}, {1,0,0}, {0,1,0} }; //store[0] will be a1 in your example.

更新2像这样打印出矩阵可能很棘手。只需尝试将其分解为不同的部分,这是一种可能的方法:

for(int i=0; i<n; i++) { //There are n main blocks(i.e. n big 3*9 horizontal rows
       for(int j=0; j<n; j++){ //In each block, we have n individual rows
           for(int k=0; k<n; k++) { //In each individual row, we have a row from a matrix
               for(int m =0; m<n; m++) { //for the row in the matrix, there are n elements
                   cout << store[i*n+k][j][m]<<" ";
               }
               cout << " ";
           }
           cout << endl;
       }
       if(i!=n-1)
           cout<< endl; //avoid a new line at the very end.
   }