Delphi array initialization

后端 未结 3 851
挽巷
挽巷 2021-01-04 01:19

I currently have this, and it sucks:

type TpointArray = array [0..3] of Tpoint;

class function rotationTable.offsets(pType, rotState, dir: integer): TpointA         


        
3条回答
  •  失恋的感觉
    2021-01-04 01:57

    You cannot because you cannot express in the code body a point in the way in which you can express it in the const section.

    However you can do some tricks in order to have your life easier, especially if you have a reasonable number of points.

    You can implement a simple procedure like this (code not tested):

    procedure BlendDimensions(aXArray, aYArray: TIntegerDynArray; var aResult: TPointArray);
    var
      nCount: integer;
      i: integer;
    
    begin
      nCount:=High(aXArray);
      if nCount <> High(aYArray) then 
        Exception.Create('The two dimension arrays must have the same number of elements!');
    
      SetLength(aResult, nCount);
      for i:=0 to nCount do
      begin
        aResult[i].X:=aXArray[i]; //simple copy
        aResult[i].y:=aYArray[i];
      end;
    end;
    

    ...where TIntegerDynArray is the RTL's dynamic array of integers. (In fact it will work with any dynamic array). Also, TPointArray in the above example is also dynamic.

    So, in order to do your job, you can do like this:

    procedure Foo;
    var
      myXCoords, myYCoords: TIntegerDynArray; //temp arrays
      myPoints: TPointArray; //this is the real thing
    
    begin
      myXCoords:=TIntegerDynArray.Create( 1, 2, 3, 4, 5, 6, 7, 8, 9,10);
      myYCoords:=TIntegerDynArray.Create(21,32,34,44,55,66,65,77,88,92); //...for example 
      BlendDimensions(myXCoords, myYCoords, myPoints); //build the real thing
     //use it...
    end;
    

    Things to note:

    • You see clearly which are your points
    • You can be very productive in this way
    • You can use BlendDimensions also on other things not only on this one
    • You can easily expand BlendDimensions for 3 (or more) dimensions
    • ...but beware because a copy is involved. :-) With today PCs, the weakpoint will be, by far, your hand. :-) You will get tired to type much more quickly till the copy time will be even noticed.

    HTH

提交回复
热议问题