Search code examples
arraysdelphidelphi-2009

Is there a way to find the index of an item of an array of pointers?


Is there a way to find the index of an item of an array of pointers ?

The code is like this:

type

  TArrayItem = record
   Field1: string;
   Field2: integer;
   Field3: boolean;
  end;

var 
  MyItem: TArrayItem; 
  MyArray: array[1..100] of TArrayItem;

Let's say I take an item from the array (MyItem:=MyArray[20];). After this I sort the array and the item locations are changed; Now, how can I find the new index of MyItem ?


Solution

  • You don't have an array of pointers. Unlike a class, which is a reference type, a record is a value type. The way you have declared the array, the item data is copied whenever you do an assignment. So hen you assign an array item to MyItem, you are making a copy of that item's data, you are not obtaining a pointer to the original item.

    In any case, whether you have an array of items or an array of pointers to items, the answer is the same: the only way to find an item in an array is to loop through the array manually, eg:

    var 
      MyItem: TArrayItem; 
      MyArray: array[1..100] of TArrayItem;
      I: Integer;
    
    MyItem := MyArray[20];
    
    // sort the array...
    
    for I := Low(MyArray) to High(MyArray) do
    begin
      if (MyArray[I].Field1 = MyItem.Field1) and
         (MyArray[I].Field2 = MyItem.Field2) and
         (MyArray[I].Field3 = MyItem.Field3) then
      begin
        // item was found at index I...
      end;
    end;
    

    Otherwise, dynamically allocate your items on the heap and store their pointers in a TList or TList<T>, as they expose IndexOf() methods. And sorting would be faster since you are only moving pointers around, not complete copies of data.