RAD Studio VCL Reference
|
TComparer is a generic base for classes that implement the IComparer interface.
TComparer<T> = class(TInterfacedObject, IComparer<T>);
template <T> class TComparer : public TInterfacedObject, public IComparer<T>;
Use TComparer as a base for custom comparer classes. The Compare method is abstract and must be implemented in descendant classes.
TComparer also provides the possibility to create a default comparer for a given data type.
Delphi Examples:
{ This example demonstrates the usage of TComparer. The example assumes two memos and three buttons are present on the form. } type { Declare a new custom comparer } TIntStringComparer = class(TComparer<String>) public function Compare(const Left, Right: String): Integer; override; end; { TIntStringComparer } function TIntStringComparer.Compare(const Left, Right: String): Integer; begin { Transform the strings into ints and perform the comparison } Result := StrToInt(Left) - StrToInt(Right); end; procedure TForm3.SortMemos(const Comparer: IComparer<String>); var List: TList<String>; I: Integer; begin { Create a new list of strings with our custom comparer } List := TList<String>.Create(Comparer); { Populate the list with numbers in the memo } for I := 0 to InMemo.Lines.Count - 1 do List.Add(InMemo.Lines[I]); { Sort the list } List.Sort(); { Copy the list with numbers to the memo } OutMemo.Clear; for I := 0 to List.Count - 1 do OutMemo.Lines.Add(List[I]); { Free resources } List.Free(); end; procedure TForm3.btCustomSortClick(Sender: TObject); begin { Use our custom comparer } SortMemos(TIntStringComparer.Create()); end; procedure TForm3.btDefaultSortClick(Sender: TObject); begin { Use the default provided comparer } SortMemos(TComparer<String>.Default); end; procedure TForm3.btOrdinalSortClick(Sender: TObject); begin { Use the ordinal string comparer } SortMemos(TStringComparer.Ordinal); end;
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
|
What do you think about this topic? Send feedback!
|