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

I need to implement a binary search in a TObjectList that uses a custom resolver, I suppose using TCustomComparer.

Purpose: binary search returns instances in the list that match a specific property parameter.

For instance:

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 return TMyClass instances to a list that also has index == 1.

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

Delphi's new help is rather scarce and scattered around what is hard to find, and I am not familiar with all the nuances of the new Delphi generics.

So - how do I do this in Delphi XE using Generics.TObjectList?

(using Delphi XE).

TIA

+4
source share
1 answer

The help file is really a bit limited. I usually just read the source code of Generics.Defaults and Generics.Collections . In any case, you need to provide IComparer<TMyClass> . There are many ways to do this. 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 do not want to use an anonymous function, you can implement Comparison another way. For example, a method of an object or a function of a class, or even a simple old-fashioned function other than OOP. It must 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 .

+4
source

Source: https://habr.com/ru/post/1432550/


All Articles