打印二维数组



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

3 2 0 0 0 0 0 0 0 0
1 4 3 0 0 0 0 0 0 0
2 4 0 0 0 0 0 0 0 0
2 4 0 0 0 0 0 0 0 0
1 3 0 0 0 0 0 0 0 0
4 2 5 1 0 0 0 0 0 0
1 3 0 0 0 0 0 0 0 0
2 3 0 0 0 0 0 0 0 0
2 3 0 0 0 0 0 0 0 0

我需要这样打印:

3 1 2 2 1 4 1 2 2
2 4 4 4 3 2 3 3 3
3       5
1

我该如何使用c++来实现这一点?

请注意,没有空行。如果整列中只有零,则不应该有endl

您需要迭代并打印出每个元素。您可以通过交换用于从数组中获取值的索引来翻转元素。

#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;
}

请记住,如果交换ij,则需要交换gridWidthgridHeight

为了避免混淆,std::setw(cellWidth)是打印固定宽度文本(比如必须始终为两个字符长的文本(的一种方便方法。它可以打印出任何内容,并在其中添加空格,使其长度合适。

对矩阵进行转置,进行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;

最新更新