多维数组 [][] 与 [,] [英] Multidimensional Array [][] vs [,]

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

问题描述

double[][] ServicePoint = new double[10][9]; // <-- gives an error (1)
double[,] ServicePoint = new double[10,9]; // <-- ok (2)

它们有什么区别?(1) 报错,原因是什么?

What's their difference? (1) yields an error, what's the reason?

double d = new double[9]
ServicePoint[0] = d;

使用 (2) 会提示错误.为什么?

using (2) will prompt an error. Why?

推荐答案

一个是数组数组,一个是二维数组.前者可以是锯齿状的,后者是均匀的.

One is an array of arrays, and one is a 2d array. The former can be jagged, the latter is uniform.

也就是说,一个 double[][] 可以是:

That is, a double[][] can validly be:

double[][] x = new double[5][];

x[0] = new double[10];
x[1] = new double[5];
x[2] = new double[3];
x[3] = new double[100];
x[4] = new double[1];

因为数组中的每个条目都是对double 数组的引用.使用锯齿状数组,您可以像在第二个示例中一样对数组进行赋值:

Because each entry in the array is a reference to an array of double. With a jagged array, you can do an assignment to an array like you want in your second example:

x[0] = new double[13];

关于第二项,因为它是一个统一的二维数组,你不能将一维数组分配给一行或一列,因为你必须同时索引行和列,这会让你归结为一个 双重:

On the second item, because it is a uniform 2d array, you can't assign a 1d array to a row or column, because you must index both the row and column, which gets you down to a single double:

double[,] ServicePoint = new double[10,9];

ServicePoint[0]... // <-- meaningless, a 2d array can't use just one index.

更新:

根据您的问题澄清一下,您的 #1 出现语法错误的原因是因为您有这个:

To clarify based on your question, the reason your #1 had a syntax error is because you had this:

double[][] ServicePoint = new double[10][9];

并且您不能在构建时指定第二个索引.关键是 ServicePoint 不是一个二维数组,而是一个一维数组(数组),因此由于您正在创建一个一维数组(数组),因此您只指定一个索引:

And you can't specify the second index at the time of construction. The key is that ServicePoint is not a 2d array, but an 1d array (of arrays) and thus since you are creating a 1d array (of arrays), you specify only one index:

double[][] ServicePoint = new double[10][];

然后,当你创建数组中的每一项时,每一项也是数组,所以那么你可以指定它们的维度(可以不同,因此术语锯齿em> 数组):

Then, when you create each item in the array, each of those are also arrays, so then you can specify their dimensions (which can be different, hence the term jagged array):

ServicePoint[0] = new double[13];
ServicePoint[1] = new double[20];

希望有帮助!

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

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