列表和BinarySearch索引并非每一个都正确 [英] List and BinarySearch index not every correct

查看:37
本文介绍了列表和BinarySearch索引并非每一个都正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我再次遇到有关列表和二进制搜索的问题。通常,我有:

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;

我在数组MyArr中加载值,并希望在列表TMyList中查找元素MyArr(包含所有值) ,然后我使用:

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));

具有这样定义的比较:

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;

现在,我的问题是,并非每个结果都是正确的。从某种意义上说,我经常有正确的元素索引,而其他时候,我随便有对应于其他元素的其他索引。
我可以解决吗?我哪里有错?

我只想在TMyArr中找到MyArr对应的索引。
非常感谢。

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.

推荐答案

您的比较函数很好如果二进制搜索无法正常工作,那只能是因为列表没有按照比较定义的顺序排序。填充完毕后以及开始搜索之前,请调用列表中的排序函数。调用排序时,必须确保它使用您的比较功能。

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.

这篇关于列表和BinarySearch索引并非每一个都正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆