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

2023-09-04 00:55:30 作者:罪″

我想初始化整数值的2维数组-1。当我创建一个新的数组,它会自动用0填充。 我知道我可以用2次做到这一点,但我想应该有这样做的,而阵列正在构建(这样我就不必两次通过它)的一些方法,所以这不是0,提供值将被插入。可能吗? 如果不是数组的初始建设过程中,有一些其他时间或code节约的方式,还是我坚持了2个周期?

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?

推荐答案

通过多维数组的循环是最有可能的最好的办法,除非阵列足够小,直接在code初始化。

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

如果您使用的是交错数组,你可以初始化第一子阵列,然后使用 Array.Copy 将这些值复制到对方子阵。这仍然需要一个迭代通过第一子阵列,并通过N-1个外的数组一个循环,但复制操作会比环路更快。

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.

 
精彩推荐
图片推荐