c++ - 如何将二维数组存储在单个数组中并用 C++ 打印它们?
问题描述
这是存储和打印的正确方法吗?
int array[5];
int a1[3][3], a2[3][3], a3[3][3], a4[3][3], a5[3][3];
int array[0] = a1[3][3];
int array[1] = a2[3][3];
int array[2] = a3[3][3];
int array[3] = a4[3][3];
int array[4] = a5[3][3];
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
a1[i][j] = 0;
}
}
同样,填充其余数组。
现在印刷,
for(int i=0;i<5;i++) {
cout<<array[i];
}
没有得到预期的输出。
如何从数组中打印 a1、a2、a3、a4 和 a5?
解决方案
因此,如果您想要固定大小的数组,请使用内置的 C++ std::array,而不是使用旧的普通 c 数组。如果范围应该是动态的,您可以std::array
使用std::vector
. 查看不同的定义:
#include <array>
#include <iostream>
// a 2D-array is nothing else, than an array containing anotehr array
// what we do, is to define an array with size 3 containing an array with size 3
// this equals int a[3][3];
// this we do 5 times as requested
std::array<std::array<int, 3>, 3> a1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::array<std::array<int, 3>, 3> a2 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::array<std::array<int, 3>, 3> a3 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::array<std::array<int, 3>, 3> a4 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::array<std::array<int, 3>, 3> a5 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// now for the array which should contain the other arrays:
// we define a size of 5
// and it should contain the array which contains the array both of size 3
std::array<std::array<std::array<int, 3>, 3>, 5> the_array;
int main() {
// we directly assign the array specifier to the value
// which should contain the specified array
the_array[0] = a1;
the_array[1] = a2;
the_array[2] = a3;
the_array[3] = a4;
the_array[4] = a5;
// now we cannot print the arrays at once,
// we have to iterate "down" to the int to print it
for(auto sub_array2D : the_array) { // iterate over the array containing the 5 arrays
for(auto sub_array1D : sub_array2D) { // now iterate over one array in the array of the 2d array
for(auto elem : sub_array1D) { // at last, access the int element and print it out
std::cout << elem << " ";
}
std::cout << "\t"; // formatting
}
std::cout << "\n"; // formatting
}
return 0;
}
推荐阅读
- google-colaboratory - Google Colaboratory:有没有办法扩大运行代码的结果单元格的高度?
- android - 在库模块中添加 .so 文件作为依赖项
- pytorch - How do I flatten a tensor in pytorch?
- php - 无法从 php 脚本向 android 应用程序发送通知
- javascript - 当我专注于输入标签时,移动键盘向上移动
- php - 使用 PHP MYSQLi 如何仅使用 action_type DR 和 CR 管理债务人和债权人
- oracle - 从查询中获取列名(不是从表中)
- amazon-web-services - 如何在 AWS Api 网关映射模板中使用 IF 条件。我可以在不使用 foreach 的情况下使用 if 条件吗?
- android - google-api-client-android 和 firestore 给出 DexArchiveMergerException 构建错误
- c# - 将点从一个三角形转换为另一个三角形