如何在ada中分配除one之外的所有元素?
如果我有这个
element_to_ignore : integer := 3;
a : array(1..4) := (5,3,2,6);
b : array(1..a'length-1) := a( all but element_to_ignore );
Run Code Online (Sandbox Code Playgroud)
我需要这个结果:
b =(5,3,6)
使用切片和数组连接.
该程序演示了如何执行此操作,并修复了代码中的一些问题(例如,您没有指定数组的元素类型):
with Ada.Text_IO; use Ada.Text_IO;
procedure Foo is
Element_To_Ignore : Integer := 3;
type Array_Of_Integer is array(Positive Range <>) of Integer;
A : Array_Of_Integer(1..4) := (5,3,2,6);
B : Array_Of_Integer(1..A'Length-1)
:= A(A'First .. Element_To_Ignore-1) &
A(Element_To_Ignore+1 .. A'Last);
begin
for I In B'Range Loop
Put_Line(Integer'Image(B(I)));
end loop;
end Foo;
Run Code Online (Sandbox Code Playgroud)
您还可以省略声明的边界A,B并让它们从初始化中获取边界.它确实意味着当Element_To_Ignore为1时,B将有界限2..4而不是1..3.这不应该是一个问题,只要你一直指B'First,B'Last和B'Range而不是使用硬连线常数.这也意味着设置Element_To_Ignore为0或5会导致B设置为(5,3,2,6).
我在这里创建了一个更精细的演示.