unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses Generics.Collections; {引用泛型單元}
{從字符串數組中查找}
procedure TForm1.Button1Click(Sender: TObject);
var
arr: array of string;
num: Integer;
begin
{構建動態數組}
SetLength(arr, 5);
arr[0] := 'aaa';
arr[1] := 'bbb';
arr[2] := 'ccc';
arr[3] := 'ddd';
arr[4] := 'eee';
{查找}
TArray.BinarySearch<string>(arr, 'ddd', num);
{顯示查找結果}
if num < Length(arr) then {如果 num = Length(arr) 就是沒找到}
ShowMessage(IntToStr(num)); {3}
end;
{從整數數組中查找}
procedure TForm1.Button2Click(Sender: TObject);
var
arr: array of Integer;
num: Integer;
begin
{構建動態數組}
SetLength(arr, 5);
arr[0] := 11;
arr[1] := 22;
arr[2] := 33;
arr[3] := 44;
arr[4] := 55;
{查找}
TArray.BinarySearch<Integer>(arr, 44, num);
{顯示查找結果}
if num < Length(arr) then {如果 num = Length(arr) 就是沒找到}
ShowMessage(IntToStr(num)); {3}
end;
end.