[英]SubArray of a 2d array with non-zero lower bounds
扩展名:
public static T[,] SubArray<T>(this T[,] values, int row_min, int row_max, int col_min, int col_max)
{
int num_rows = row_max - row_min + 1;
int num_cols = col_max - col_min + 1;
T[,] result = new T[num_rows, num_cols];
int total_cols = values.GetUpperBound(1) + 1;
int from_index = row_min * total_cols + col_min;
int to_index = 0;
for (int row = 0; row <= num_rows - 1; row++)
{
Array.Copy(values, from_index, result, to_index, num_cols);
from_index += total_cols;
to_index += num_cols;
}
return result;
}
适用于GetLowerBound(0)
和GetLowerBound(1)
等于GetLowerBound(0)
二维数组。 例如如果
int[,] arr1 = new int[5, 4];
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 4; ++j)
{
arr1[i, j] = i + j;
}
}
var arr1sub = arr1.SubArray(2, 3, 1, 3);
然后arr1sub
是具有 2 行和 3 列的二维数组(两者的索引都从 0 开始)
3 4 5
5 6 7
现在,如果我查看初始数组作为索引不从零开始的情况:
int[,] arr2 = (int[,])Array.CreateInstance(typeof(int), new int[] { 5, 4 }, new int[] { 3, 1 });
for (int i = arr2.GetLowerBound(0); i <= arr2.GetUpperBound(0); ++i)
{
for (int j = arr2.GetLowerBound(1); j <= arr2.GetUpperBound(1); ++j)
{
arr2[i, j] = i - arr2.GetLowerBound(0) + j - arr2.GetLowerBound(1);
}
}
var arr2sub = arr2.SubArray(5, 6, 2, 4);
前面代码片段的最后一行将在该行的SubArray
扩展函数中触发异常
Array.Copy(values, from_index, result, to_index, num_cols);
对于row
等于零。
我了解二维数组arr1
(具有基于零的索引)在内存中布局,但不了解二维数组arr2
(具有非基于零的索引)在内存中的Array.Copy
,因此我对Array.Copy
使用一定是错误的在这种情况下,但我不明白为什么。
您没有正确计算total_cols
和from_index
。
public static T[,] SubArray<T>(this T[,] values, int row_min, int row_max, int col_min, int col_max)
{
int num_rows = row_max - row_min + 1;
int num_cols = col_max - col_min + 1;
T[,] result = new T[num_rows, num_cols];
int total_cols = values.GetLength(1);
int from_index = (row_min - values.GetLowerBound(0)) * total_cols + (col_min - values.GetLowerBound(1)) + values.GetLowerBound(0);
int to_index = 0;
for (int row = 0; row <= num_rows - 1; row++)
{
Array.Copy(values, from_index, result, to_index, num_cols);
from_index += total_cols;
to_index += num_cols;
}
return result;
}
total_cols
是显而易见的; 至于from_index
,我找不到任何关于它的文档,但看起来sourceIndex
中的Array.Copy
从sourceArray.GetLowerBound(0)
开始计数,而不是从零开始计数,鉴于此索引在行间不断增长,这不一定立即显而易见和列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.