如何用不同的默认值初始化多维数组

时间:2021-02-12 13:42:46

I am trying to initialize 2-dimensional array of integer values with -1. When I create a new array, it is automatically filled with 0. I know I can do it with 2 for cycles, but I imagine there should be some way of doing this while the array is being build (so I don't have to go through it two times), so that instead of 0, provided value would be inserted. Is it possible? If not during the initial building of the array, is there some other time or code saving way, or am I stuck with 2 for cycles?

我尝试用-1来初始化整数值的二维数组。当我创建一个新数组时,它会自动填充0。我知道我可以用2来表示周期,但我想在构建数组时应该有某种方法来实现它(所以我不需要对它进行两次遍历),这样就可以插入值而不是0。是可能的吗?如果不是在数组的初始构建过程中,是否有其他的时间或代码保存方式,或者我是否在循环中使用2 ?

2 个解决方案

#1


11  

With a multidimensional array, the loops are most likely the best approach, unless the array is small enough to initialize directly in code.

对于多维数组,循环很可能是最好的方法,除非数组足够小,可以直接在代码中初始化。

If you're using a jagged array, you could initialize the first sub-array, then use Array.Copy to copy these values into each other sub-array. This will still require one iteration through the first sub array, and one loop through N-1 outer arrays, but the copy operation will be faster than the loops.

如果您正在使用一个不规则数组,您可以初始化第一个子数组,然后使用数组。将这些值复制到彼此的子数组中。这仍然需要一个迭代遍历第一个子数组,一个循环遍历N-1外部数组,但是复制操作将比循环快。

#2


17  

Try something like this: int[,] array2D = new int[,] { { -1 }, { -1 }, { -1 }, { -1} };

尝试以下操作:int[,] array2D = new int[,] {-1}, {-1}, {-1};

or with dimension int[,] array2D = new int[4,2] { { -1,-1 }, { -1,-1 }, { -1,-1 }, {-1,-1} };

或与维度int[,]array2D = new int[4,2]{ { 1 1 },{ 1 },{ 1 },{ 1 1 } };

#1


11  

With a multidimensional array, the loops are most likely the best approach, unless the array is small enough to initialize directly in code.

对于多维数组,循环很可能是最好的方法,除非数组足够小,可以直接在代码中初始化。

If you're using a jagged array, you could initialize the first sub-array, then use Array.Copy to copy these values into each other sub-array. This will still require one iteration through the first sub array, and one loop through N-1 outer arrays, but the copy operation will be faster than the loops.

如果您正在使用一个不规则数组,您可以初始化第一个子数组,然后使用数组。将这些值复制到彼此的子数组中。这仍然需要一个迭代遍历第一个子数组,一个循环遍历N-1外部数组,但是复制操作将比循环快。

#2


17  

Try something like this: int[,] array2D = new int[,] { { -1 }, { -1 }, { -1 }, { -1} };

尝试以下操作:int[,] array2D = new int[,] {-1}, {-1}, {-1};

or with dimension int[,] array2D = new int[4,2] { { -1,-1 }, { -1,-1 }, { -1,-1 }, {-1,-1} };

或与维度int[,]array2D = new int[4,2]{ { 1 1 },{ 1 },{ 1 },{ 1 1 } };