泛型数组
如用 TArray<Word> 代替 array of Word, 还可以使用 TArray 类提供的算法(就是少了点).
--------------------------------------------------------------------------------
uses Generics.Collections, Generics.Defaults;
{测试 TArray 的 Sort 方法}
procedure TForm1.Button1Click(Sender: TObject);
var
arr: TArray<string>; //同 array of string
s: string;
begin
SetLength(arr, 5);
arr[0] := 'aaa';
arr[1] := 'AAA';
arr[2] := '111';
arr[3] := '333';
arr[4] := '222';
TArray.Sort<string>(arr);
Memo1.Clear;
for s in arr do Memo1.Lines.Add(s); //111 222 333 AAA aaa
end;
{测试 TArray 的 BinarySearch 方法}
procedure TForm1.Button2Click(Sender: TObject);
var
arr: TArray<Integer>; //同 array of Integer
i,n: Integer;
begin
SetLength(arr, 5);
for i := 0 to Length(arr) - 1 do arr[i] := Integer(Sqr(i));
Memo1.Clear;
for i := Low(arr) to High(arr) do Memo1.Lines.Add(IntToStr(arr[i]));
if TArray.BinarySearch<Integer>(arr, 4, n) then ShowMessage(IntToStr(n)); //2, 也就是第三个
if TArray.BinarySearch<Integer>(arr, 5, n) then ShowMessage(IntToStr(n)); //找不到时, 不能根据 n 的值判断
end;
{自定义排序器}
procedure TForm1.Button3Click(Sender: TObject);
var
arr: TArray<Integer>;
num: Integer;
begin
SetLength(arr, 5);
arr[0] := 2;
arr[1] := 4;
arr[2] := 3;
arr[3] := 1;
arr[4] := 5;
TArray.Sort<Integer>(arr, TComparer<Integer>.Construct(
function (const a,b: Integer): Integer
begin
Result := b - a;
end
));
Memo1.Clear;
for num in arr do Memo1.Lines.Add(IntToStr(num)); //5 4 3 2 1
end;
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/archive/2013/03/03/2941340.html