打印二维数组,C++ [英] Printing 2d array, C++

查看:67
本文介绍了打印二维数组,C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自 Matlab,在那里我只需右键单击 2D 矩阵即可查看其中内容的类似 excel 的可视化.现在我正在 C++ (Visual Studio) 中工作,并且正在寻找类似于二维数组的东西,例如像这样的可视化:

I'm coming from Matlab where I could just right-click a 2D matrix to see an excel-like visualization of what's inside it. Now I'm working in C++ (Visual Studio) and am looking for something similar for 2d arrays, eg a visualization like:

myArray = [ 1 2 3
            4 5 6
            7 8 9 ]

在 C++ 中执行此类操作的最佳方法是什么?

What the best way to do something like this in C++?

推荐答案

首先,这不是 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.

这篇关于打印二维数组,C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆