Remover elemento de uma array

Delphi

15/07/2008

Boa tarde,

Estou criando uma rotina e preciso que seja feita a exclusão do elemento de uma array conforme a opção selecionada pelo usuário.
Encontrei um exemplo mas não estou conseguindo excluir o último elemento. Segue abaixo a rotina se alguém tiver uma idéia pois a sintaxe

anArray[aPosition].free;

Não fuciona, na hora de compilar exibe mensagem de erro (record, object or type class required ), estou utilizando Delphi 6.


procedure TfrmHierarquia.DeleteElement(var anArray:TArrayCustos; const aPosition:integer);
var
lg, j : integer;
begin
lg := length(anArray);
if aPosition > lg-1 then
exit
else
if aPosition = lg-1 then
begin //if is the last element
//if TSomeType is a TObject descendant don´t forget to free it
//for example anArray[aPosition].free;
Setlength(anArray, lg -1);
exit;
end;
for j := aPosition to lg-2 do//we move all elements from aPosition+1 left...
anArray[j] := anArray[j+1];//...with a position
SetLength(anArray, lg-1);//now we have one element less
//that´s all...
end;


Exemplo de utilização.

No evento click do botão

begin
DeleteElement(matriz_mo,0);
end;


Obrigado.

Airton


Airoosp

Airoosp

Curtidas 0

Respostas

Fabianosales

Fabianosales

15/07/2008

Boa tarde Airton.

Se TArrayCustos for um vetor de um tipo de dados nativo, não vai funcionar mesmo, pois o método ´Free´ é declarado em TObject.
Como você não postou a declaração do tipo TArrayCusto, vou listar as funções para os dois casos (array de tipos nativos e arrays de objetos), ok?
Primeiro os tipos de dados usados.
type
  TStringArray = array of string;   //array de um tipo nativo
  TObjectArray = array of TObject;  //array de objetos

Agora as funções:
function RemoveElement(var pArray: TStringArray; const pIndex:integer):boolean;
var
  i :integer;
begin
  Result := (pIndex <= High(pArray)) and (pIndex >= Low(pArray));
  if not(Result) then
    raise EListError.Create(
      Format(´List index is out of bounds (¬s).´, [pIndex]))
  else
    begin
      for i:= pIndex to High(pArray)-1 do
        pArray[i] := pArray[i+1];
      SetLength(pArray, Length(pArray)-1);
      Result := true;
    end;
end;

function RemoveElement(var pArray: TObjectArray; const pIndex:integer):boolean;
var
  i :integer;
begin
  Result := (pIndex <= High(pArray)) and (pIndex >= Low(pArray));
  if not(Result) then
    raise EListError.Create(
      Format(´List index is out of bounds (¬s).´, [pIndex]))
  else
    begin
      for i:= pIndex to High(pArray)-1 do
        begin
          if Assigned(pArray[i]) then
             FreeAndNil(pArray[i]);
          pArray[i] := pArray[i+1];
        end;
      SetLength(pArray, Length(pArray)-1);
      Result := true;
    end;
end;



GOSTEI 0
POSTAR