在其他编程语言中,我可以int array[23][23]用来声明每个维度中包含23个元素的2D数组.我如何在Haxe中实现同样的目标?
目前我需要这样做:
var arr:Array<Array<Int>> = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
Run Code Online (Sandbox Code Playgroud)
但是当阵列增长到更大的尺寸时,我再也无法宣布它了.
the*_*rns 12
最好的方法是利用Haxe 3中提供的数组解析:
var bigArray:Array<Array<Int>> = [for (x in 0...10) [for (y in 0...10) 0]];
Run Code Online (Sandbox Code Playgroud)
数组理解是用于制作数组的非常好且简洁的语法.上面的代码将生成一个10x10数组,填充0.你可以在这里阅读更多相关信息.
如果您出于某种原因正在运行Haxe 2,那么最好的方法是使用for循环填充它们,如前所述.
正如你在John的答案评论中所说,我所知道的2D阵列没有内置,但创建一个并不难.
在这里,我制作了两个辅助函数,一个使用haxe.ds.Vector,这是Haxe 3中的新功能,并针对固定大小的集合进行了优化.另一个使用普通数组,因此在某些平台上可能会更慢,技术上不是固定宽度,只是初始化为一定大小.
import haxe.ds.Vector;
class Vector2DTest
{
static function main()
{
// 2D vector, fixed size, sometimes faster
var v2d = Vector2D.create(3,5);
v2d[0][0] = "Top Left";
v2d[2][4] = "Bottom Right";
trace (v2d);
// [[Top Left,null,null,null,null],[null,null,null,null,null],[null,null,null,null,Bottom Right]]
// 2D array, technically variable size, but you'll have to initialise them. Sometimes slower.
var a2d = Array2D.create(3,5);
a2d[0][0] = "Top Left";
a2d[2][4] = "Bottom Right";
trace (a2d);
// [[Top Left,null,null,null,null],[null,null,null,null,null],[null,null,null,null,Bottom Right]]
}
}
class Vector2D
{
public static function create(w:Int, h:Int)
{
var v = new Vector(w);
for (i in 0...w)
{
v[i] = new Vector(h);
}
return v;
}
}
class Array2D
{
public static function create(w:Int, h:Int)
{
var a = [];
for (x in 0...w)
{
a[x] = [];
for (y in 0...h)
{
a[x][y] = null;
}
}
return a;
}
}
Run Code Online (Sandbox Code Playgroud)
Vector2D只适用于Haxe 3(本月晚些时候发布),Array2D也适用于Haxe 2.
您可以使用1D数组伪造 2D数组:
class Array2 extends Array
{
public var pitch(default, null): Int;
public function new(x: Int, y: Int)
{
pitch = x;
super(x * y);
}
public function get(x: Int, y: Int)
{
return this[y * pitch + x];
}
}
Run Code Online (Sandbox Code Playgroud)