Ir al contenido


Foto

TList de enteros


  • Por favor identifícate para responder
7 respuestas en este tema

#1 jc

jc

    Member

  • Miembros
  • PipPip
  • 40 mensajes
  • LocationMojácar, Almería, España

Escrito 13 noviembre 2010 - 05:26

Hola a todos

Estaba haciendo un pequeño proyecto y me surgió hacer una lista de enteros, pensé usar un TList, pero nunca lo había usado y tampoco encontré mucha información, así que me armé un pequeño ejempo, pongo un poco de lo que hice:



delphi
  1. //    VaciarLista
  2. procedure TVprincipal.VaciarLista;
  3. var
  4.     i: integer;
  5.     n: ^integer;
  6. begin
  7.     for i := 0 to (ListaEnteros.Count - 1) do
  8.         begin
  9.         n := ListaEnteros[i];
  10.         Dispose(n);
  11.         end;
  12.     ListaEnteros.Clear;
  13. end;
  14.  
  15. //    OnClose
  16. procedure TVprincipal.FormClose(Sender: TObject; var CloseAction: TCloseAction);
  17. begin
  18.     VaciarLista;
  19.     ListaEnteros.Free;
  20.     CloseAction := caFree;
  21. end;
  22.  
  23. //    OnShow
  24. procedure TVprincipal.FormShow(Sender: TObject);
  25. begin
  26.     ListaEnteros := TList.Create;
  27.     Randomize;
  28. end;
  29.  
  30. //    edNum KeyPress
  31. //
  32. //    edNum es un componente TEditMask
  33. procedure TVprincipal.edNumKeyPress(Sender: TObject; var Key: char);
  34. var
  35.     n: ^integer;
  36. begin
  37.     if Key = #13 then
  38.     begin
  39.     New(n);
  40.     n^ := StrToInt(edNum.Text);
  41.     ListaEnteros.Add(n);
  42.     edNum.Clear;
  43.     end;
  44. end;
  45.  
  46.  
  47. //    bLlenarClick
  48. //
  49. //    mete 10 enteros aleatorios en la lista
  50. procedure TVprincipal.bLlenarClick(Sender: TObject);
  51. var
  52.     i: integer;
  53.     n: ^integer;
  54. begin
  55.   for i := 1 to 10 do
  56.         begin
  57.         New(n);
  58.         n^ := Random(100);
  59.         ListaEnteros.Add(n);
  60.         end;
  61. end;



Funcionar funciona, mi duda es si lo hago bien, si libero bien toda la memoria y eso, si hay una forma más sencilla, etc.

Saludos
  • 0

#2 Marc

Marc

    Advanced Member

  • Moderadores
  • PipPipPip
  • 1.484 mensajes
  • LocationMallorca

Escrito 14 noviembre 2010 - 11:31

Bueno una simple matriz de enteros y un contador apuntando al último valor asignado también te servirían perfectamente. No hay necesidad de complicarse mucho para mantener una lista de enteros.

Saludos.
  • 0

#3 jc

jc

    Member

  • Miembros
  • PipPip
  • 40 mensajes
  • LocationMojácar, Almería, España

Escrito 16 noviembre 2010 - 12:41

Hola

Bueno una simple matriz de enteros y un contador apuntando al último valor asignado también te servirían perfectamente. No hay necesidad de complicarse mucho para mantener una lista de enteros.


El problema es que no hay forma de saber cuantos enteros habrá en la lista, depende de las acciones del usuario. La lista va a contener un índice de los registros borrados en un archivo de datos, para sobreescribirlos a la hora de guardar uno nuevo.

En principio cabe esperar que los registros borrados no sean muchos, y, como se van sobreescribiendo, es de esperar que la lista no crezca mucho, pero nada impide que crezca bastante y con un array siempre puedo quedarme corto o pasarme en exceso, por eso se me ocurrió hacer esa lista.

Saludos
  • 0

#4 Marc

Marc

    Advanced Member

  • Moderadores
  • PipPipPip
  • 1.484 mensajes
  • LocationMallorca

Escrito 16 noviembre 2010 - 01:47

Hola.

Hola


Bueno una simple matriz de enteros y un contador apuntando al último valor asignado también te servirían perfectamente. No hay necesidad de complicarse mucho para mantener una lista de enteros.


El problema es que no hay forma de saber cuantos enteros habrá en la lista, depende de las acciones del usuario. La lista va a contener un índice de los registros borrados en un archivo de datos, para sobreescribirlos a la hora de guardar uno nuevo.

En principio cabe esperar que los registros borrados no sean muchos, y, como se van sobreescribiendo, es de esperar que la lista no crezca mucho, pero nada impide que crezca bastante y con un array siempre puedo quedarme corto o pasarme en exceso, por eso se me ocurrió hacer esa lista.

Saludos


No es que me gusten mucho, pero también tienes las matrices dinámicas.

Se declaran : var M: array of integer;

Y después le puedes ir cambiando el tamaño con el procedimiento SetLength.

Ejplo (pondremos el tamaño de la matriz anterior a 50 enteros) : SetLength(M, 50);

Saludos.
  • 0

#5 eduarcol

eduarcol

    Advanced Member

  • Administrador
  • 4.483 mensajes
  • LocationVenezuela

Escrito 16 noviembre 2010 - 02:28

y pregunto, no es mas facil un TStringList y hacer un cast???  (h)



delphi
  1. MiEntero := StrtoInt(Milista.Strings[0]);


  • 0

#6 jc

jc

    Member

  • Miembros
  • PipPip
  • 40 mensajes
  • LocationMojácar, Almería, España

Escrito 16 noviembre 2010 - 03:08

Hola

y pregunto, no es mas facil un TStringList y hacer un cast???  (h)



delphi
  1. MiEntero := StrtoInt(Milista.Strings[0]);



Ahora mismo lo tengo así  :cheesy:

Pensaba que estaría un poquito más ¿elegante?, ¿correcto? empleando enteros y ahorrándome la conversión.

Saludos
  • 0

#7 cadetill

cadetill

    Advanced Member

  • Moderadores
  • PipPipPip
  • 994 mensajes
  • LocationEspaña

Escrito 19 noviembre 2010 - 08:45

Buenas,

Un día que tenía poco que hacer, hice una clase TIntegerList que básicamente se basaba en un TStringList haciendo un cast, pero que de cara al programador es totalmente transparente. Aquí te la dejo por si te interesa



delphi
  1. interface
  2.  
  3. uses
  4.   Classes, SysUtils;
  5.  
  6. type
  7.   TIntegerList = class
  8.   private
  9.     List: TStringList;
  10.     function GetCount: Integer;
  11.   protected
  12.     function Get(Index: Integer): integer; virtual;
  13.     procedure Put(Index, Item: integer); virtual;
  14.   public
  15.     constructor Create; virtual;
  16.     destructor Destroy; override;
  17.  
  18.     function Add(Item: integer): Integer;
  19.     function IndexOf(Item: integer): Integer;
  20.     function First: integer;
  21.     function Last: integer;
  22.     function Remove(Item: integer): Integer;
  23.  
  24.     procedure Clear; virtual;
  25.     procedure Delete(Index: Integer);
  26.     procedure Insert(Index, Item: integer);
  27.     procedure Move(CurIndex, NewIndex: Integer);
  28.  
  29.     property Count: Integer read GetCount;
  30.     property Items[Index: Integer]: integer read Get write Put; default;
  31.   end;
  32.  
  33. implementation
  34.  
  35. { TIntegerList }
  36.  
  37. constructor TIntegerList.Create;
  38. begin
  39.   List := TStringList.Create;
  40. end;
  41.  
  42. destructor TIntegerList.Destroy;
  43. begin
  44.   if Assigned(List) then FreeAndNil(List);
  45.  
  46.   inherited;
  47. end;
  48.  
  49. function TIntegerList.Add(Item: integer): Integer;
  50. begin
  51.   Result := -1;
  52.   if Assigned(List) then Result := List.Add(IntToStr(Item));
  53. end;
  54.  
  55. procedure TIntegerList.Clear;
  56. begin
  57.   List.Clear;
  58. end;
  59.  
  60. procedure TIntegerList.Delete(Index: Integer);
  61. begin
  62.   List.Delete(Index);
  63. end;
  64.  
  65. function TIntegerList.First: integer;
  66. begin
  67.   Result := -1;
  68.   if Assigned(List) and (List.Count > 0) then Result := StrToInt(List[0])
  69. end;
  70.  
  71. function TIntegerList.Get(Index: Integer): integer;
  72. begin
  73.   Result := StrToInt(List[Index]);
  74. end;
  75.  
  76. function TIntegerList.IndexOf(Item: integer): Integer;
  77. begin
  78.   Result := -1;
  79.   if Assigned(List) then Result := List.IndexOf(IntToStr(Item));
  80. end;
  81.  
  82. procedure TIntegerList.Insert(Index, Item: integer);
  83. begin
  84.   List.Insert(Index, IntToStr(Item));
  85. end;
  86.  
  87. function TIntegerList.Last: integer;
  88. begin
  89.   Result := -1;
  90.   if Assigned(List) then Result := StrToInt(List[List.Count - 1]);
  91. end;
  92.  
  93. procedure TIntegerList.Move(CurIndex, NewIndex: Integer);
  94. begin
  95.   List.Move(CurIndex, NewIndex);
  96. end;
  97.  
  98. procedure TIntegerList.Put(Index, Item: integer);
  99. begin
  100.   List[Index] := IntToStr(Item);
  101. end;
  102.  
  103. function TIntegerList.Remove(Item: integer): Integer;
  104. begin
  105.   Result := -1;
  106.   if Assigned(List) then
  107.   begin
  108.     Result := Self.IndexOf(Item);
  109.     if Result >= 0 then Self.Delete(Result);
  110.   end;
  111. end;
  112.  
  113. function TIntegerList.GetCount: Integer;
  114. begin
  115.   Result := List.Count;
  116. end;
  117.  
  118. end.



Nos leemos

  • 0

#8 jc

jc

    Member

  • Miembros
  • PipPip
  • 40 mensajes
  • LocationMojácar, Almería, España

Escrito 24 noviembre 2010 - 12:42

Hola

.... Aquí te la dejo por si te interesa ...


Gracias por el aporte.

Tenía pensado precisamente hacer una clase para que manejara la lista de enteros, como ya hice todo el código que puse al principio para manejar la lista de enteros, ya la haré así. Aunque tomaré nota de como la hiciste tú.

Saludos
  • 0




IP.Board spam blocked by CleanTalk.