且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

打印二维数组,C++

更新时间:2022-06-16 02:18:19

首先,这不是 C++ 中数组声明/初始化的正确语法.我不知道是否有任何 IDE 可以为您可视化数组,但是您可以在代码中使用两个 for 循环来实现它.这也显示了数组的正确语法.

First of all, this is not correct syntax for declaration/initialization of arrays in C++. I don't know if there's any IDE that will visualize an array for you, but you can do it in code with just two for loop like this. This also shows the correct syntax for arrays.

#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
  int myArray[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
  };

  for (int i=0; i<3; ++i) {
    for (int j=0; j<3; ++j)
      cout << myArray[i][j] << ' ';
    cout << endl;
  }

  return 0;
}

或者,如果你想方便调试,你可以像这样定义一个预处理器指令

Or, if you want to make it convenient for debugging, you can define a preprocessor directive like this

#include <iostream>
#include <iomanip>

using namespace std;

#define test_array(name,ni,nj,w)      \
  cout << #name " = {\n";             \
  for (int i=0; i<ni; ++i) {          \
    cout << "  ";                     \
    for (int j=0; j<nj; ++j)          \
      cout << setw(w+1) << myArray[i][j]; \
    cout << endl;                     \
  }                                   \
  cout << '}' << endl;

int main(int argc, char **argv)
{
  int myArray[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
  };

  test_array(myArray,3,3,2)

  return 0;
}

第四个参数将允许您设置列宽,以便您可以很好地对齐.

The fourth argument will allow you to set column width, so you can have nice alignment.