我需要用矩阵实现操作,矩阵的大小必须是可变的。我想出的唯一解决方案是使用链表:
[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] ...
...
但在我看来有点复杂。是否有更好(更容易)的解决方案?
谢谢你们!
答案 0 :(得分: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;
这种寻址方式比链接列表快得多。
答案 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;