我想創建一個陣列并以以下方式訪問它以進行讀取和寫入切片操作(即一次多個元素):
- 如果索引在范圍內,照常訪問它們
- 如果第二個索引小于第一個索引,請按如下方式訪問資料:(
First .. A'Last & A'First .. (First 5)事實證明這不能按原樣作業,因為連接結果上限超出范圍)
我想出了以下示例來演示該問題:
with Ada.Text_IO;
use Ada.Text_IO;
procedure Test_Modular is
type Idx is mod 10;
type My_Array is array (Idx range <>) of Integer;
A: My_Array(Idx) := (
0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5,
6 => 6, 7 => 7, 8 => 8, 9 => 9
);
First: constant Idx := 7;
S: constant My_Array := A(First .. First 5);
begin
for I in S'range loop
Put_Line(Idx'Image(I) & " --> " & Integer'Image(S(I)));
end loop;
end Test_Modular;
在示例中,它5是靜態的,編譯器警告我如下:
$ gnatmake -o test_modular test_modular.adb
x86_64-linux-gnu-gcc-10 -c test_modular.adb
test_modular.adb:18:19: warning: loop range is null, loop will not execute
x86_64-linux-gnu-gnatbind-10 -x test_modular.ali
x86_64-linux-gnu-gnatlink-10 test_modular.ali -o test_modular
運行程式時,我觀察到以下內容:
$ ./test_modular
即沒有編譯器警告預測的輸出。
現在我想知道:有沒有辦法像這樣撰寫切片A(First .. First 5)并使其“環繞”,以便訪問的資料與這個修改后的示例程式中的資料相同,除非不必在代碼中明確區分這兩種情況?
with Ada.Text_IO;
use Ada.Text_IO;
procedure Test_Modular_2 is
type Idx is mod 10;
type My_Array is array (Idx range <>) of Integer;
A: My_Array(Idx) := (
0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5,
6 => 6, 7 => 7, 8 => 8, 9 => 9
);
First: constant Idx := 7;
S1: constant My_Array := A(First .. A'Last);
S2: constant My_Array := A(A'First .. (First 5));
begin
for I in S1'range loop
Put_Line(Idx'Image(I) & " --> " & Integer'Image(S1(I)));
end loop;
for I in S2'range loop
Put_Line(Idx'Image(I) & " --> " & Integer'Image(S2(I)));
end loop;
end Test_Modular_2;
uj5u.com熱心網友回復:
嘗試以下方法:
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
type Idx is mod 10;
type My_Array is array (Idx range <>) of Integer;
function rotate (arr : My_Array; head : Idx; tail : Idx) return My_Array is
P1_Len : Natural;
P2_Len : Natural;
begin
P1_Len :=
(if head <= tail then Natural (tail) - Natural (head) 1
else Natural (arr'Last) - Natural (head) 1);
P2_Len := (if head <= tail then 0 else Natural (tail) 1);
declare
Result : My_Array (0 .. Idx (P1_Len P2_Len - 1));
begin
if head <= tail then
Result := arr (head .. tail);
else
Result (0 .. Idx (P1_Len - 1)) := arr (head .. arr'Last);
Result (Idx (P1_Len) .. Result'Last) := arr (0 .. tail);
end if;
return Result;
end;
end rotate;
procedure print (A : My_Array) is
begin
for V of A loop
Put (V'Image);
end loop;
New_Line;
end print;
A : My_Array :=
(0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8,
9 => 9);
head : Idx := 7;
tail : Idx := head 5;
begin
Put_Line ("Head: " & head'Image & " Tail:" & tail'Image);
Put_Line ("Initial value order:");
print (A);
declare
S1 : My_Array := rotate (A, head, tail);
begin
Put_Line ("Rotated value order:");
print (S1);
end;
end Main;
上面的 rotate 函式旋轉由 head 和 tail 索引值指示的一組值,將 head 值放置在 rotate 回傳的陣列的開頭。此示例顯示生成的陣列可能包含的元素少于作為引數傳遞給函式的陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/522689.html
標籤:数组片阿达ada2012
上一篇:使用鍵和值陣列生成地址字串
下一篇:如何修改重復內容的陣列?
