質問
行列を使用して操作を実装する必要があり、行列のサイズは可変である必要があります。私が思いついた唯一の解決策は、リンクリストを使用することです:
[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] ...
...
しかし、私には少し複雑に思えます。.より良い(そして簡単な)解決策はありますか?
ありがとうございます!
解決
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;
他のヒント
最新のパスカルバリアント(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;
この種類のアドレス指定は、リンクされたリストに従うよりもはるかに高速です。
所属していません StackOverflow