我有一些TList和BinarySearch問題。我有這樣的結構:TList和BinarySearch錯誤
PDoubleEstr = record
Double: array [1..2] of Integer;
Count: Integer;
end;
TDoubleEstr = TList<PDoubleEstr>;
,並聲明:
var oDoubleEstr: TDoubleEstr;
然後,我用這個功能正確初始化列表:
procedure Initialize;
var
iIndex1, iIndex2: Integer;
rDoubleEstr: PDoubleEstr;
begin
oDoubleEstr.Clear;
for iIndex1 := 1 to 89 do
for iIndex2 := Succ(iIndex1) to 90 do
begin
with rDoubleEstr do
begin
Double[1] := iIndex1;
Double[2] := iIndex2;
Count := 0;
end;
oDoubleEstr.Add(rDoubleEstr);
end;
end;
現在,我定義這個過程:
procedure Element(const First: Integer; const Second: Integer; var Value: PDoubleEstr);
begin
with Value do
begin
Double[1] := First;
Double[2] := Second;
end;
end;
then在我的主要程序中:
procedure Main;
var
Value: PDoubleEstr;
Index: Integer;
flag: boolean;
begin
Element(89, 90, Value);
flag := oDoubleEstr.BinarySearch(Value, Index, TDelegatedComparer<PDoubleEstr>.Construct(Compare));
Writeln(Flag:5, oDoubleEstr[Index].Double[1]:5, oDoubleEstr[Index].Double[2]:5);
end;
它變成了一個錯誤。從某種意義上說,索引爲「索引」的元素不符合我輸入的元素。 當然,oDoubleEstr排序正確,不明白我的錯誤。 比較的結構是這樣定義的:
function TDouble.Compare(const Left, Right: PDoubleEstr): Integer;
begin
Result := Sign(Left.Double[1] - Right.Double[2]);
end;
,我認爲這是錯誤的概念,但是作爲解決它不被理解。 一般來說,我想檢查元素是否存在,如果存在則獲取索引。作爲元素,我的意思是在我的情況下只有字段Double。 我試着更好地解釋,我的列表,以便填充:
1 2 // element 0
1 3
......
1 90
......
88 89
88 90
89 90 // element 4004
如果我設置元素(89,90),它應該是把我作爲指標值:4004和真實,如發現或否則爲false。 感謝您的幫助。
恩,我應該寫嗎?我只想簡單地在我的列表元素「Double」中找到只包含兩個數字,並檢查它是否存在以及是否存在於它的位置(索引)。我試圖通過一些例子來研究這個解決方案。你能給我更多的細節嗎?非常感謝。 –
如果您想根據Double []'數組中的兩個值進行比較和搜索,請使用Ville提供的功能。但是,如果您的值足夠大,仍然會出現溢出錯誤。我懷疑是這種情況,但我指出了完整性。 –
@Marcello對,我想我已經到了現在的底部。查看更新。二元搜索只有在列表按您提供的比較函數確定的順序排列時纔有效。 –