delphi 使用泛型的 TArray 从动态数组中查找指定元素  
官方Delphi 学习QQ群: 682628230(三千人)
频道

delphi 使用泛型的 TArray 从动态数组中查找指定元素


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(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(arr, 44, num);

  {显示查找结果}
  if num < Length(arr) then {如果 num = Length(arr) 就是没找到}
    ShowMessage(IntToStr(num)); {3}
end;

end.

推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.037243843078613 seconds