问题
i have some problem again about list and binarysearch. In general, i have:
type
TMyArr = array [1..5] of Integer;
PMyList = record
Comb: TMyArr;
... // other fields
end;
TMyList = TList<PMyList>;
var
MyArr: TMyArr;
MyList: TMyList;
rMyList: PMyList;
i load value in array MyArr and want find element MyArr (with all values in it) in list TMyList, then i use:
rMyList.Comb := MyArr;
MyList.BinarySearch(rMyList, iIndex3, TDelegatedComparer<PMyList>.Construct(Compare));
with Compare so defined:
function CompareInt(const Left, Right: Integer): Integer;
begin
if Left < Right then
Result := -1
else if Left > Right then
Result := 1
else
Result := 0;
end;
function Compare(const Left, Right: PMyList): Integer;
begin
Result := CompareInt(Left.Comb[1], Right.Comb[1]);
if Result = 0 then
Result := CompareInt(Left.Comb[2], Right.Comb[2]);
if Result = 0 then
Result := CompareInt(Left.Comb[3], Right.Comb[3]);
if Result = 0 then
Result := CompareInt(Left.Comb[4], Right.Comb[4]);
if Result = 0 then
Result := CompareInt(Left.Comb[5], Right.Comb[5]);
end;
Now, my problem is that not every result is correct. In sense that often i have correct index of element and other time i have other index corresponding to other element, in casual.
As i can solve it? Where i have mistake?
I want only find index corresponding of MyArr in TMyArr.
Thanks again very much.
回答1:
Your Compare
function is just fine. If the binary search fails to work correctly then that can only be because the list is not ordered by the order defined by Compare
. Call the Sort
function on the list once you have finished populating, and before you start searching. When you call Sort
, you must make sure that it use your compare function.
来源:https://stackoverflow.com/questions/8368243/list-and-binarysearch-index-not-every-correct