1

行列を使用して操作を実装する必要があり、行列のサイズは可変でなければなりません。私が思いついた唯一の解決策は、リンクされたリストを使用することです:

[pointer to this row, pointer to another row] -> [element 1,1; link to another element] -> [element 1,2,  link to another element] -> .... -> [nil]
     |
     v
[pointer to this row, pointer to another row] ...
     ...

しかし、それは少し複雑に思えます..より良い(そしてより簡単な)解決策はありますか?

君たちありがとう!

4

2 に答える 2

1

最新の Pascal バリアント (Delphi) では、動的な (ランタイム サイズの) 配列を作成できます。

言語が多次元動的配列をサポートしていない場合は、アドレス指定を自分で処理できます。

var
  rows, cols, total, i, j : integer;
  cell : datatype;
begin
  rows := ...;
  cols := ...;
  total := rows * cols;
  matrix := ...(total);

  cell := matrix[i * cols + j]; // matrix[row=i,col=j]

end;

この種のアドレス指定は、リンクされたリストをたどるよりもはるかに高速です。

于 2009-05-01T09:58:50.547 に答える
1

1 つの方法は、GetMemを使用して正確に十分なメモリを割り当てることです。GetMem は広くサポートされているようです。

const
    MAXMATRIXDATA: Word = 10000;
type
    TMatrixDataType = Word;
    TMatrixData = array[0..MAXMATRIXDATA] of TMatrixDataType;
    PMatrixData = ^TMatrixData;
    TMatrix = record
        Rows, Cols: Word;
        MatrixData: PMatrixData;
        end;
    PMatrix = ^TMatrix;

function CreateMatrix(Rows, Cols: Word): PMatrix;
var
    Ret: PMatrix;
begin
    New(Ret);
    Ret^.Rows := Rows;
    Ret^.Cols := Cols;
    GetMem(Ret^.MatrixData,Rows*Cols*SizeOf(TMatrixDataType));
    CreateMatrix := Ret;
end;

function GetMatrixData(Matrix: PMatrix; Row, Col: Word): TMatrixDataType;
begin
    GetMatrixData := Matrix^.MatrixData^[(Row*Matrix^.Cols)+Col];
end;

procedure SetMatrixData(Matrix: PMatrix; Row, Col: Word; Val: TMatrixDataType);
begin
    Matrix^.MatrixData^[(Row*Matrix^.Cols)+Col] := Val;
end;
于 2009-05-01T10:08:41.163 に答える