我有一个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 |
问题是,以这种方式分配值是时间成本的,并且该ALG需要尽可能高效。
我认为多维数组实际上是内存中的1D数组,因此,如果我可以访问每个元素的指针,那么我可以直接分配任何计算值的值。问题是我无法找到一种创建指向通用类数组(或第一个元素(的指针的方法。
基本上,我正在尝试编写一个通用函数(它将接受任何原始类型作为数组的数据类型,并接受任何多维数组(:
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));