2010-07-24 78 views
5

將int []轉換爲int [,]我想要一個函數將單維數組int [480000]轉換爲大小爲int [800,600]的2d數組。 你能幫我解決這個問題嗎?嘗試使用C#

回答

5
public static T[,] Convert<T>(this T[] source, int rows, int columns) 
{ 
    int i = 0; 
    T[,] result = new T[rows, columns]; 

    for (int row = 0; row < rows; row++) 
    for (int col = 0; col < columns; col++) 
     result[row, col] = source[i++]; 
    return result; 
} 
1
for (int i = 0; i < 800; ++i) { 
    for (int j = 0; j < 600; ++j) { 
     m[i, j] = a[600*i + j]; 
    } 
} 

根據您的存儲佈局,您可能需要使用i + 800*j代替。

+1

j可以高達600,當然:) – user11977 2010-07-24 05:57:56

+0

謝謝@smerriman的。感謝我得到的複製粘貼。 – 2010-07-24 06:09:51

1

UPD(固定填充柱,而不是按行,這裏是正確的版本)

private static T[,] create2DimArray<T>(T[] array, int n) 
     { 
      if (n <= 0) 
       throw new ArgumentException("Array M dimension cannot be less or equals zero","m"); 
      if (array == null) 
       throw new ArgumentNullException("array", "Array cannot be null"); 
      if (array.Length == 0) 
       throw new ArgumentException("Array cannot be empty", "array"); 

      int m = array.Length % n == 0 ? array.Length/n : array.Length/n + 1; 
      var newArr = new T[m,n]; 
      for (int i = 0; i < arr.Length; i++) 
      { 
       int k = i/n; 
       int l = i % n; 
       newArr[k, l] = array[i]; 
      } 

      return newArr; 
     } 

對於要素1000000它的作品在我的機器上33毫秒。真的很快1 for循環。

+2

1)'arr.Length' - >'array.Length'。 2)注意:它將按照您通常所期望的方式逐列複製數組,而不是逐行復制數組。 – 2010-07-24 06:29:32

+0

對不起,錯了。我已經更新了答案,我在尺寸和索引方面有誤。在第二個參數中,我們傳遞了我們需要的列數,然後計算行數並填充新的二維數組。 – 2010-07-26 12:36:48

5

你真的想要物理移動數據還是800x600'視圖'就足夠了?
你可以使用像這樣的包裝:

// error checking omitted 
class MatrixWrapper<T> 
{ 
    private T[] _data; 
    private int _columns; 

    public MatrixWrapper(T[] data, int rows, int columns) 
    { 
     _data = data; 
     _columns = columns; 
     // validate rows * columns == length 
    } 

    public T this[int r, int c] 
    { 
     get { return _data[Index(r, c)]; } 
     set { _data[Index(r, c)] = value; } 
    } 

    private int Index(int r, int c) 
    { 
     return r * _columns + c; 
    } 
} 

而且你使用它像:

 double[] data = new double[4800]; 
     var wrapper = new MatrixWrapper<double>(data, 80, 60); 
     wrapper[2, 2] = 2.0;