如何初始化二维数组的数组? [英] How to initialize an array of 2D-arrays?

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

问题描述

我有二维数组的数组。例如,它是这样的:

I have an array of 2D-arrays. For example, it is like:

{{{0, 0, 1}, {1, 0, 0}}
{{0, 0, 3}, {2, 1, 2}, {2, 2, 1}, {3, 0, 0}}
{{0, 0, 7}, {3, 2, 6}, {6, 2, 3}, {6, 3, 2}, {7, 0, 0}}}

但如果我写

int [,][] arrays={{{0, 0, 1}, {1, 0, 0}}
                  {{0, 0, 3}, {2, 1, 2}, {2, 2, 1}, {3, 0, 0}}
                  {{0, 0, 7}, {3, 2, 6}, {6, 2, 3}, {6, 3, 2}, {7, 0, 0}}};



编译器会抱怨预期。

the compiler will complain "; expected".

如果我写

int [,][] arrays={new int[,] {{0, 0, 1}, {1, 0, 0}}
                  new int[,] {{0, 0, 3}, {2, 1, 2}, {2, 2, 1}, {3, 0, 0}}
                  new int[,] {{0, 0, 7}, {3, 2, 6}, {6, 2, 3}, {6, 3, 2}, {7, 0, 0}}};



编译器会抱怨

the compiler will complain

嵌套数组初始化预期。

那么,为什么会出现这种情况,什么是初始化的正确方法?

So why does this happen and what is the correct way of initialization?

推荐答案

您正在尝试创建不规则数组。你的阵列有 N 行,因此你的第一方应该是[]不是[,]。元中的每一行( N 的指数)是二维数组,所以你需要使用 [,] 。最后,您可以通过修复INT改变您的问题 [] [] INT [] [,]

You're trying to create jagged array. Your array has n rows so your first square should be [] not [,]. Element in each row (index of n) is 2D array so you need to use [,]. Finally, you can fix your problem by change int [,][] to int[][,].

int[][,] arrays = {
    new int[,] {{0, 0, 1}, {1, 0, 0}},
    new int[,] {{0, 0, 3}, {2, 1, 2}, {2, 2, 1}, {3, 0, 0}},
    new int[,] {{0, 0, 7}, {3, 2, 6}, {6, 2, 3}, {6, 3, 2}, {7, 0, 0}}
};

这篇关于如何初始化二维数组的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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