Vector
Vector

Reputation: 11753

Implementing Custom Binary Search for TObjectList<myClass> (Delphi XE)

I need to implement a binary search on TObjectList that uses a custom comparer, I believe using TCustomComparer.

Goal: binary search returns instances in the list that conform to a particular property parameter.

For example:

TMyClass=class
    public
     Index:integer
end;

TMyObjectList=TObjectList<TMyClass>;

begin
  ...
    aMyClass.Index:=1;
    aMyObjectList.binarysearch(aMyClass, aMyClassRef) 
  ...
end;

Or simply:

 begin
   ...
     aMyObjectList.binarysearch(1, aMyClassRef) 
   ...
 end;

I want to loop and get back instances of TMyClass in the list that also have Index==1.

In C++, overloading the '==' operator achieves this goal.

The new Delphi 'help' is rather sparse and scattered around making things hard to find, and I'm not that familiar with all the nuances of the new Delphi generics.

So - how do I do it in Delphi XE with the Generics.TObjectList?

(Using Delphi XE).

TIA

Upvotes: 4

Views: 2489

Answers (1)

David Heffernan
David Heffernan

Reputation: 613481

The help file is indeed a little limited here. I generally just read the source code to Generics.Defaults and Generics.Collections. Anyway, you need to provide an IComparer<TMyClass>. There's lots of ways to do that. For example, using an anonymous function:

var
  List: TObjectList<TMyClass>;
  Target: TMyClass;
  Index: Integer;
  Comparer: IComparer<TMyClass>;
  Comparison: TComparison<TMyClass>;
....    
Comparison :=
  function(const Left, Right: TMyClass): Integer
  begin
    //Result := ??;//your comparison rule goes here
  end;
Comparer := TComparer<TMyClass>.Construct(Comparison);
List.BinarySearch(Target, Index, Comparer);

If you don't want to use an anonymous function you can implement Comparison some other way. For example a method of some object, or a class function, or even just a plain old fashioned non-OOP function. It just has to have the same signature as above.

As always with comparison functions, return <0 if Left<Right, >0 if Left>Right and 0 if Left=Right.

Upvotes: 5

Related Questions