[英]Assign 1D array values to multidimensional array, of unknown dimensions / type
我有一個N維數組,我希望能夠為其分配任何原始值。 (一種類型適用於單個數組,但alg必須適用於所有原始類型)。
我寫了一種方法可以做到這一點:
var element = Array.CreateInstance(dataType, dataDims);
foreach (var index in GetIndexes(dataDims))
{
element.SetValue(SomeKindOfValue, index);
}
函數GetIndexes生成給定維度的所有可能的索引:
public static IEnumerable<int[]> GetIndexes(int[] dims)
{
int lastIndex = dims.Length - 1;
int lastDim = dims[lastIndex];
int[] Index = new int[dims.Length];
int currentDim = lastIndex;
while (currentDim >= 0)
{
if (currentDim == lastIndex)
{
for (int i = 0; i < lastDim; i++)
{
yield return Index;
Index[currentDim]++;
}
Index[currentDim] = 0;
currentDim--;
continue;
}
else
{
if (Index[currentDim] == dims[currentDim] - 1)
{
Index[currentDim] = 0;
currentDim--;
continue;
}
else
{
Index[currentDim]++;
currentDim = lastIndex;
continue;
}
}
}
}
示例:對於GetIndexes(new int [] {4,2,3}),輸出將是:
0, 0, 0 |
0, 0, 1 |
0, 0, 2 |
0, 1, 0 |
0, 1, 1 |
0, 1, 2 |
1, 0, 0 |
1, 0, 1 |
1, 0, 2 |
1, 1, 0 |
1, 1, 1 |
1, 1, 2 |
2, 0, 0 |
2, 0, 1 |
2, 0, 2 |
2, 1, 0 |
2, 1, 1 |
2, 1, 2 |
3, 0, 0 |
3, 0, 1 |
3, 0, 2 |
3, 1, 0 |
3, 1, 1 |
3, 1, 2 |
問題在於,以這種方式分配值非常耗時,並且這種算法需要盡可能高效。
我以為多維數組實際上是內存中的1d數組,因此,如果我可以訪問每個元素的指針,那么我可以直接將值分配為不帶任何計算的值。 問題是我無法找到一種方法來創建指向通用類Array(或其第一個元素)的指針。
基本上,我正在嘗試編寫一個泛型函數(它將接受任何原始類型作為數組的數據類型,並接受任何多維數組):
public static unsafe void SetElementsByPointer(int[,] array, int[] values)
{
if (values.Length != array.LongLength)
throw new Exception("array and values length mismatch.");
fixed (int* pStart = array)
{
for (int i = 0; i < array.LongLength; i++)
{
int* pElement = pStart + i;
*pElement = values[i];
}
}
}
我將欣賞將值設置為n維數組的任何其他想法,但是指針方法似乎是最有效的,只是我無法弄清楚
提前致謝。
要復制內容,您可以使用以下代碼: https : //dotnetfiddle.net/vTzJv4
// 1D array
int[] values = new int[] {
1, 2, 3,
4, 5, 6
};
// 2D array
int[,] marr = new int[2,3];
// Copy here
System.Buffer.BlockCopy((Array)values, 0, (Array)marr, 0, (int)marr.LongLength * sizeof(int));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.