问题描述
我将一个数组初始化为
Double[][] myarr = Enumerable.Repeat(new double[12], 13).ToArray();
然后在循环中我正在增加
之类的值myarr[0][0]++;
这会导致所有值,例如Myarr [1] [0],Myarr [2] [0],Myarr [3] [0] ..... Myarr [12] [0]递增一个.
使用for循环时不会发生这个问题(0-12)我正在初始化
myarr[i] = new double[12];
为什么这样?
推荐答案
其他答案解释了问题.解决方案是在每个迭代中创建一个新数组,例如
double[][] myarr = Enumerable.Range(0, 13) .Select(ignored => new double[12]) .ToArray();
其他推荐答案
with new double[12]您正在创建对双打数组的引用,然后重复参考 12次,因此Myarr [0..n]将参考一个内存区域.
您可以使用效率方法来解决问题
static T[][] CreateArray<T>(int rows, int cols) { T[][] array = new T[rows][]; for (int i = 0; i < array.GetLength(0); i++) array[i] = new T[cols]; return array; }
或使用自定义重复方法调用操作的每个步骤:
public static IEnumerable<TResult> RepeatAction<TResult>(Action<TResult> elementAction, int count) { for (int i = 0; i < count; i++) { yield return elementAction(); } yield break; } usage RepeatAction(()=>new double[12], 12);
其他推荐答案
这是因为new double[12]在内存中创建一个单个数组对象-Enumobles.Repeat只是为您提供对该数组的多个引用.
问题描述
I initialized an Array as
Double[][] myarr = Enumerable.Repeat(new double[12], 13).ToArray();
Then in a loop i am incrementing values like
myarr[0][0]++;
This causes all values like myarr[1][0], myarr[2][0], myarr[3][0] ..... myarr[12][0] to increment by one.
This problem is not occurring when using a for loop (0-12) i am initializing like
myarr[i] = new double[12];
Why is this so?
推荐答案
Other answers have explained the problem. The solution is to create a new array on each iteration, e.g.
double[][] myarr = Enumerable.Range(0, 13) .Select(ignored => new double[12]) .ToArray();
其他推荐答案
With new double[12] you are creating reference to array of doubles, and then you repeate the reference 12 times, so myarr[0..n] will have reference to one memory region.
You can use the folowing method to resolve thw issue
static T[][] CreateArray<T>(int rows, int cols) { T[][] array = new T[rows][]; for (int i = 0; i < array.GetLength(0); i++) array[i] = new T[cols]; return array; }
Or with custom Repeat method which calls action every step:
public static IEnumerable<TResult> RepeatAction<TResult>(Action<TResult> elementAction, int count) { for (int i = 0; i < count; i++) { yield return elementAction(); } yield break; } usage RepeatAction(()=>new double[12], 12);
其他推荐答案
It's because new double[12] creates a single array object in memory - Enumerable.Repeat is simply providing you with multiple references to that array.