2012년 10월 18일 목요일

제네릭 이해를 돕기 위한 간단한 사용(TArray)

델파이가 2009 버전부터 Generic을 지원한다고하는데 아마추어 입장에서는 별로 변화를 못 느꼈습니다. 제네릭에 대한 일반적인 것은 도서를 참고하시고, 저는 Generics.Collectons 에 있는 델파이가 만들어 놓은 제네릭 클라스를 살펴보도록 하겠습니다.

당연 최상위는 Tobject 가 있고 그아래 TArray 가 있으며 그로부터 여러가지 클래스등이 있네요. 우선 TArray 를 살펴 보겠습니다. 이것은 class 메소드만으로 이루어 졌다고 보면 됩니다. 그중 중요한 것이 Create, Sort, BinarySearch 입니다.

uses Generics.Collections, Generics.Defaults;
 
{Test the Sort method of TArray}
procedure TForm1.Button1Click(Sender: TObject);
var
     Arr: TArray<string>; //same as 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;
 
{Test TArray's BinarySearch method}
procedure TForm1.Button2Click(Sender: TObject);
var
     Arr: TArray<Integer>; //same as 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, which is the third
     If TArray.BinarySearch<Integer>(arr, 5, n) then ShowMessage(IntToStr(n)); //When not found, can't judge according to the value of n
end;
 
{custom sorter}
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;







댓글 없음:

tensorflow gpu 사용하기에서

 tensorflow 설치시 주의해야 한다. # Anything above 2.10 is not supported on the GPU on Windows Native python - m pip install "tensorflow<2.11...