我想初始化一个二维整数数组为-1。当我创建一个新数组时,它会自动填充为0。
我知道可以使用2个for循环来实现,但是我想象中应该有一种在构建数组时就能完成的方法(这样我就不必通过两次遍历来完成),以便插入提供的值而不是0。这可行吗?
如果不能在数组初始构建期间完成,是否有其他时间或代码节省的方法,或者我只能使用2个for循环?
int[,] array2D = new int[,] { { -1 }, { -1 }, { -1 }, { -1} };
或者使用维度 int[,] array2D = new int[4,2] { { -1,-1 }, { -1,-1 }, { -1,-1 }, {-1,-1} };
mat = [[0] * 5] * 5 # wrong
mat = [[0] * 5] for _ in range(5)] # correct
因为您多次复制内部数组的引用,更改其中一个引用最终会更改所有引用。
mat[0][0] = 1
print(mat)
# 1 0 0 0 0
# 1 0 0 0 0
# 1 0 0 0 0
# 1 0 0 0 0
# 1 0 0 0 0
var mat = Enumerable.Repeat(Enumerable.Repeat(0, 5).ToArray(), 5).ToArray();
由于数组是引用类型,外部的 Repeat() 实际上是在复制内部数组的引用。
如果您确实需要创建和初始化多维数组而不使用 for 循环,那么也许一个自定义的帮助类会有所帮助:
static class HelperFunctions
{
public static T[][] Repeat<T>(this T[] arr, int count)
{
var res = new T[count][];
for (int i = 0; i < count; i++)
{
//arr.CopyTo(res[i], 0);
res[i] = (T[])arr.Clone();
}
return res;
}
}
然后如果你想使用它:
using static HelperFunctions;
var mat = Enumerable.Repeat(0, 5).ToArray().Repeat(5);
这样就可以了。