c++ - 打印二维数组
问题描述
我有这个二维数组 array[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;
}
请记住,如果您交换i
andj
然后您将需要交换gridWidth
and gridHeight
。
为了避免混淆std::setw(cellWidth)
,打印固定宽度文本(例如必须始终为两个字符长的文本)是一种方便的方法。它需要您打印出来的任何内容并为其添加空格以使其长度正确。
推荐阅读
- python - 尝试使用 os.rename 时出现 FileNotFoundError
- relay - 如何在参数定义中将今天的日期作为默认值 createFragmentContainer 传递
- java - 从文件中解析Java中的JSON
- ethereum - 仲裁中的公共交易卡在交易池中待处理
- r - 订购图例标签而不是向下?
- javascript - 如何在 map 函数中重用对象?
- c# - Group By 除了实例化一个类
- javascript - 如何限制我的基于 JS 浏览器的 API 应用程序?
- r - 当其中一个选项产生 NA 时,在 R 中使用 ifelse?
- php - 将base64字符串解密为jpeg图像时损坏的图像