問題
我正在用 C# 撰寫一個 Matrix 類,我知道這個類需要一個二維陣列來存盤 Matrix 物件。我的 Matrix 類的建構式采用兩個引數,即 Matrix 的 m 和 n 維。我試圖在建構式中分配陣列,但我收到錯誤
Invalid Rank Specifier. 我試過的代碼如下所示。
class Matrix
{
//make the dimensions private
private int m,n;
//The Matrix constructor needs two parameters
//The row and column dimensions
//declare the two dimension array
private int[][] array;
public Matrix(int m, int n) {
//assign the array inside the constructor
array = new int[m][n];
}
//method to allocate the Matrix
}
我的目標是首先使用維度初始化陣列,以便可以無誤地完成分配,謝謝。
uj5u.com熱心網友回復:
我覺得您要做的是創建一個多維陣列,您可以在此處了解更多資訊。
在您的情況下,這意味著您將創建一個 int[,] 陣列:
class Matrix
{
//make the dimensions private
private int m,n;
//The Matrix constructor needs two parameters
//The row and column dimensions
//declare the two dimension array
private int[,] array;
public Matrix(int m, int n) {
//assign the array inside the constructor
array = new int[m, n];
}
//method to allocate the Matrix
}
之后,您可以通過以下方式訪問您的值:
public int GetValue(int m, int n) => array[m,n];
同樣對于設定值:
public void SetValue(int m, int n) => array[m,n] = value;
uj5u.com熱心網友回復:
你實際上有一個鋸齒狀的陣列,即陣列陣列:int[][],注意二維陣列是int[,]
要初始化,int[][]您必須創建每個內部陣列:
public Matrix(int m, int n) {
array = new int[m][]; // outer array of size m which
for (int i = 0; i < n; i) // contains
array[i] = new int[n]; // arrays of length n
}
您可以使用Linq來縮短語法:
using System.Linq;
...
public Matrix(int m, int n) {
array = Enumerable
.Range(0, m)
.Select(_ => new int[n])
.ToArray();
}
編輯:可能的Matrix實作:
class Matrix {
private int[][] array;
public Matrix(int rows, int columns) {
if (rows <= 0)
throw new ArgumentOutOfRangeException(nameof(rows));
if (columns <= 0)
throw new ArgumentOutOfRangeException(nameof(columns));
array = Enumerable
.Range(0, rows)
.Select(_ => new int[columns])
.ToArray();
}
public int RowCount => array.Length;
public int ColumnCount => array[0].Length;
public int this[int row, int column] {
get {
if (row < 0 || row >= array.Length)
throw new ArgumentOutOfRangeException(nameof(row));
if (column < 0 || column >= array[row].Length)
throw new ArgumentOutOfRangeException(nameof(column));
return array[row][column];
}
set {
if (row < 0 || row >= array.Length)
throw new ArgumentOutOfRangeException(nameof(row));
if (column < 0 || column >= array[row].Length)
throw new ArgumentOutOfRangeException(nameof(column));
array[row][column] = value;
}
}
}
uj5u.com熱心網友回復:
我更喜歡對二維資料使用常規的一維陣列。就像是:
public class MyMatrix<T>
{
public int Width { get; }
public int Height { get; }
public T[] Data { get; }
public MyMatrix(int width, int height)
{
Width = width;
Height = height;
Data = new T[width * height];
}
public T this[int x, int y]
{
get => Data[y * Width x];
set => Data[y * Width x] = value;
}
}
與典型的 2D 多維方法相比,這具有一些優勢:
- 互操作性:多維陣列是一個 .Net 概念,并非在每種語言中都存在,但幾乎每種語言都有某種一維陣列。
- 序列化:大多數序列化庫處理一維陣列,對二維陣列的支持比較參差不齊。
- 性能:有時您只需要遍歷所有專案,使用支持的一維陣列可能是最快的方法。
- 避免陷阱:
.GetLength()對于多維陣列來說非常慢,如果您將值快取在回圈之外,這不是一個大問題,但如果您不知道或忘記了這一點,則可能會成為問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/346638.html
