简体   繁体   中英

How to initialize multi-dimensional array with different default value

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?

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

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

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.

In Python, this kind of 2D array initialization is wrong:

mat = [[0] * 5] * 5  # wrong
mat = [[0] * 5] for _ in range(5)]  # correct

because you are copying the reference of the inner array multiple times, and changing one of them will eventually change all.

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

In C#, we have the similar issue.

var mat = Enumerable.Repeat(Enumerable.Repeat(0, 5).ToArray(), 5).ToArray();

Since array is a reference type, the outside Repeat() are actually copying the reference of the inner array.

Then if you do have the need to create and initialize multidimensional arrays without using for loops, then maybe a custom helper class will help:

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;
    }
}

Then if you want to use it:

using static HelperFunctions;

var mat = Enumerable.Repeat(0, 5).ToArray().Repeat(5);

This will do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM