首页 > 解决方案 > 如何将二维数组存储在单个数组中并用 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++arraysc++11multidimensional-arrayc++17

解决方案


因此,如果您想要固定大小的数组,请使用内置的 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;
}

推荐阅读