首页 > 解决方案 > 打印二维数组

问题描述

我有这个二维数组 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

标签: c++arraysmultidimensional-array

解决方案


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

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

请记住,如果您交换iandj然后您将需要交换gridWidthand gridHeight

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


推荐阅读