在一个变量中存储多个 2D 数组
Store multiple 2d arrays in a variable
我正在生成一个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.
}
相关文章:
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 一个 2D 数组,并按行存储值.第一个循环用于行索引,第二个循环用于列索引
- 如何声明一个必须在C++中同时存储int和char值的2D数组
- 将.txt文件存储到 char* 2d 矢量C++中
- 在一个变量中存储多个 2D 数组
- 使用线性存储实现2D数组
- 访问表示 2D 矩阵的 1D 存储数组
- 我如何在2D数组中存储许多精灵
- 如何将元素的索引从2D数组存储到1D数组中,然后交换这些值
- 如何在C++中将字符串数据存储在字符串 2D 数组中
- 如何从文件中读取并将内容存储在动态 2D 数组中并以网格格式显示
- 将数据存储在具有可互换 x/y 坐标的 2D 矩阵中
- 创建一个动态2D数组来存储类对象
- 2D阵列和1D阵列存储比较
- 如何仅将数字值存储在给定输入文件中的2D数组中?(没有指针)
- 2D-Array 会在存储新元素时删除元素本身
- 存储2D对象阵列的最佳方法是什么
- C#/Java 如何存储 2D 数组,与C++不同?
- 如何在std::set中存储2D几何向量