S
期间,大小被固定为4)。预先分配内存以容纳所有四个矩阵。example_1.adb
with Ada.Text_IO; use Ada.Text_IO;
procedure Example_1 is
type Rows is new Natural range 0 .. 2;
type Cols is new Natural range 0 .. 2;
type Matrix is array (Rows, Cols) of Integer;
-- A 2D matrix.
type Stack is array (Natural range <>) of Matrix;
-- Stack of 2D matrices.
S : constant Stack (1 .. 4) :=
(1 => (others => (others => 1)),
2 => (others => (others => 2)),
3 => (others => (others => 3)),
4 => (others => (others => 4)));
begin
for Mtx of S loop -- using "of", not "in", such to iterate over the elements.
for R in Rows loop
Put ("[");
for C in Cols loop
Put (Mtx (R, C)'Image);
end loop;
Put_Line (" ]");
end loop;
New_Line;
end loop;
end Example_1;
example_2.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Example_2 is
type Rows is new Natural range 0 .. 2;
type Cols is new Natural range 0 .. 2;
type Matrix is array (Rows, Cols) of Integer;
-- A 2D matrix.
package Stacks is new Ada.Containers.Vectors (Natural, Matrix);
use Stacks;
subtype Stack is Stacks.Vector;
-- Stack of 2D matrices.
Empty_Stack : constant Stack := Stacks.Empty_Vector;
-- An empty stack.
S : Stack;
-- Instead of using Append (..) shown below, you can also
-- initialize the stack using:
--
-- S : Stack := Empty_Stack
-- & (others => (others => 1))
-- & (others => (others => 2))
-- & (others => (others => 3))
-- & (others => (others => 4));
begin
S.Append ((others => (others => 1)));
S.Append ((others => (others => 2)));
S.Append ((others => (others => 3)));
S.Append ((others => (others => 4)));
-- ...
for Mtx of S loop -- using "of", not "in", such to iterate over the elements.
for R in Rows loop
Put ("[");
for C in Cols loop
Put (Mtx (R, C)'Image);
end loop;
Put_Line (" ]");
end loop;
New_Line;
end loop;
end Example_2;
输出(两个示例相同)
[ 1 1 1 ]
[ 1 1 1 ]
[ 1 1 1 ]
[ 2 2 2 ]
[ 2 2 2 ]
[ 2 2 2 ]
[ 3 3 3 ]
[ 3 3 3 ]
[ 3 3 3 ]
[ 4 4 4 ]
[ 4 4 4 ]
[ 4 4 4 ]