C++ 打印二维阵列

C++ 打印二维阵列,c++,arrays,multidimensional-array,C++,Arrays,Multidimensional Array,我有这个二维数组[y][x](其中x是水平的,y是垂直的): 我需要这样打印: 3 1 2 2 1 4 1 2 2 2 4 4 4 3 2 3 3 3 3 5 1 我怎么用C++?< /P> 请注意,没有空行。如果整列中只有零,则不应该有一个endl对矩阵进行转置,制作2个循环(外部和内部),仅当no大于零时打印,并为每个零打印空间。当您再次返回外部循环时,请打印新行。类似的内容应该会对您有所帮助 for (int i = 0; i < y; i++)

我有这个二维数组[y][x](其中x是水平的,y是垂直的):

我需要这样打印:

3 1 2 2 1 4 1 2 2
2 4 4 4 3 2 3 3 3
  3       5
          1
<>我怎么用C++?< /P>
请注意,没有空行。如果整列中只有零,则不应该有一个
endl

对矩阵进行转置,制作2个循环(外部和内部),仅当no大于零时打印,并为每个零打印空间。当您再次返回外部循环时,请打印新行。

类似的内容应该会对您有所帮助

for (int i = 0; i < y; i++)
    for (int j = 0; j < x; j++)
        if (array[i][j] != 0)
            cout << array[i][j];
        else
            cout << " ";
    cout << endl;
for(int i=0;icout您需要迭代并打印出每个元素。可以通过交换用于从数组中获取值的索引来翻转元素

#include<iostream>
#include<iomanip>

int gridWidth = 10;
int gridHeight = 10;
int cellWidth = 2;

for (int i = 0; i < gridHeight; i++){
    bool anyVals = false;
    for (int j = 0; j < gridWidth; j++){
        int val = array[i][j]; //Swap i and j to change the orientation of the output
        if(val == 0){
             std::cout << std::setw(cellWidth) << " ";
        }
        else{
             anyVals = true;
             std::cout << std::setw(cellWidth) << val;
        }
    }
    if(anyVals)
        std::cout << std::endl;
}
#包括
#包括
int gridWidth=10;
int gridHeight=10;
int-cellWidth=2;
对于(int i=0;istd::不欢迎使用堆栈溢出。请阅读、获取、阅读以及。最后学习如何创建。如果您的行在其他数字之间有
0
s,会发生什么情况,即:
3 2 0 0 1 0…
?如果我使用它,我会得到很多空行,因为所有的共谋都没有数字。非常感谢!但我认为
bool anyVals=false;
应该高于第二个for循环(但在第一个for循环内),这样它就不会每次都变回false。更改后,一切都会正常工作!!
#include<iostream>
#include<iomanip>

int gridWidth = 10;
int gridHeight = 10;
int cellWidth = 2;

for (int i = 0; i < gridHeight; i++){
    bool anyVals = false;
    for (int j = 0; j < gridWidth; j++){
        int val = array[i][j]; //Swap i and j to change the orientation of the output
        if(val == 0){
             std::cout << std::setw(cellWidth) << " ";
        }
        else{
             anyVals = true;
             std::cout << std::setw(cellWidth) << val;
        }
    }
    if(anyVals)
        std::cout << std::endl;
}