將int []轉換爲int [,]我想要一個函數將單維數組int [480000]轉換爲大小爲int [800,600]的2d數組。 你能幫我解決這個問題嗎?嘗試使用C#
Q
嘗試使用C#
5
A
回答
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
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;
相關問題
- 1. 嘗試使用C#和Ionic.dll
- 2. 嘗試使用Npgsql更新C#列
- 3. C#嘗試使用XmlNode讀取頁面
- 4. 嘗試使用AngularJs和C#的WebAPI
- 5. 嘗試使用BeautifulSoup
- 6. 嘗試使用笨
- 7. 嘗試使用PHP
- 8. 嘗試使用python
- 9. 嘗試使用jqxgrid
- 10. 嘗試使用LINQ
- 11. 嘗試使用OAuth
- 12. 嘗試使用JNLP
- 13. 嘗試使用AJAX
- 14. 嘗試使用LINQ2SQL
- 15. 嘗試使用shutil.move()
- 16. 嘗試使用RecursiveIteratorIterator
- 17. 嘗試使用python3.2
- 18. 嘗試使用NPOI
- 19. 嘗試使用LINQ
- 20. 嘗試使用AJAX
- 21. 嘗試使用R.
- 22. 嘗試使用Unirest
- 23. 嘗試使用context.entity.include()
- 24. 嘗試使用python
- 25. 嘗試使用AppleScript
- 26. 嘗試使用笨
- 27. 嘗試使用includeProperties
- 28. 嘗試使用JavaScript
- 29. 嘗試使用INT
- 30. 嘗試使用取
j可以高達600,當然:) – user11977 2010-07-24 05:57:56
謝謝@smerriman的。感謝我得到的複製粘貼。 – 2010-07-24 06:09:51