how to delete from Ada.Containers.Doubly_Linked_Lists |
|
Hi,
I try to get aquinted with Ada.Containers.Doubly_Linked_Lists,
which I feel may replace a homebrew list class we
use at work.
Especailly the 'for of' notation
seems nice to have.
But How do I delete an item in the list
while looping it?
I've got a sample below,
but I fell it is clumpsy.
How should a nice solution look like ?
/Björn
with Text_Io;
with Ada.Containers.Doubly_Linked_Lists;
procedure Test_List is
type Example_Type is record
A :Integer := 0;
B: Integer := 0;
end record;
procedure To_String(E : Example_Type) is
begin
Text_io.Put_Line(E.A'Img & E.B'Img);
end To_String;
begin
Text_io.Put_Line("start Ada.Containers.Doubly_Linked_Lists; ");
declare
Data : Example_Type;
package Example_Pkg is new
Ada.Containers.Doubly_Linked_Lists(Example_Type);
List : Example_Pkg.List;
begin
Text_io.Put_Line("insert 5 elements at tail, ");
for i in 1..5 loop
Data := (A => i, B => 2 * i);
List.Append(Data);
end loop;
for i of List loop
To_String(i);
end loop;
Text_io.Put_Line("Update in place");
for i of List loop
I.A := 5*I.A;
I.B := 50*I.B;
end loop;
for i of List loop
To_String(i);
end loop;
Text_io.Put_Line("delete if I.a = 15");
for c in List.Iterate loop
declare
i : Example_Type := Example_Pkg.Element(C);
begin
if I.A = 15 then
List.Delete(C); <-- program_error raised
end if;
end ;
end loop;
--works but clumplsy
declare
C_Save : Example_Pkg.Cursor;
begin
for c in List.Iterate loop
declare
i : Example_Type := Example_Pkg.Element(C);
begin
if I.A = 15 then
C_Save := C;
exit;
end if;
end ;
end loop;
List.Delete(C_Save);
end;
for i of List loop
To_String(i);
end loop;
Text_io.Put_Line("done");
end;
end Test_List;
sample run:
insert 5 elements at tail,
1 2
2 4
3 6
4 8
5 10
Update in place
5 100
10 200
15 300
20 400
25 500
delete if I.a = 15
Execution terminated by unhandled exception
Exception name: PROGRAM_ERROR
Message: attempt to tamper with cursors (list is busy)
|