1

In Ada, when you declare a array, you can do something like

    Work_Day : constant array (Day) of Boolean := (Mon .. Fri => True, Sat | Sun => False);

which utilizes the .. and | symbols to account for multiple elements of the array instead of having to reference each array.

I want to do something similar, but with a array of arrays, and I dont want to do it at the declaration, but instead later in the program, when I might have to redefine the initial value. I am attempting to do something like

   -- Set elements 2 through 5 of row 1 to asdf
   Array_of_Arrays(1)(2..5) := "asdf";

or

   -- Set elements 1 and 3 of row 1 to asdf2
   Array_of_Arrays(1)(1 | 3) := "asdf2"

But neither seem to be the correct syntax. Is there a way of doing this?

Thanks

4

1 に答える 1

5

The syntax

Array_of_Arrays(1)(2..5) := "asdf";

is legal, assuming that what you have is really an array of arrays. However, I'm guessing that you don't. Unlike some languages (C, Java, etc.), Ada makes a distinction between multi-dimensional arrays and "arrays of arrays". A two-dimensional array is declared something like

type Array_Type is array (1 .. 10, 1 .. 5) of Character;
Array_2D : Array_Type; 

(and similarly for 3- or higher-dimensional arrays). When you declare your array type like this, you use indexes separated by commas to refer to a single element:

Array_2D (2, 3) := 'x';

and not

Array_2D (2) (3) := 'x';  -- wrong!!  will not compile

You can't use a slice for multi-dimensional arrays:

Array_2D (1, 2..5) := "asdf";

The language designers just didn't allow that.

An array of arrays would be declared like:

type Array_Row is array (1 .. 5) of Character;
type Array_Of_Array_Type is array (1 .. 10) of Array_Row;
Array_Of_Arrays : Array_Of_Array_Type;

Now, since the array row type is separate, you don't use the multi-dimensional array syntax. To get at one character, you'd use something like

Array_Of_Arrays (2) (3) := 'x';

and it's legal to do something like

Array_Of_Arrays (1) (2..5) := "asdf";

but not

Array_Of_Arrays (1, 2..5) := "asdf";  -- syntax error

The key is to remember that in this case, each "row" of the array is a separate array object with its own array type; while in the multi-dimensional case, rows don't have their own types.

You can use either one; there are some cases where an array of arrays may be more appropriate, and some where a multi-dimensional array is more appropriate.

Since String is an array type, this also is an array of arrays:

type Array_Of_Strings is array (1 .. 10) of String(1..5);

and this is legal:

A : Array_Of_Strings;

A (3) (4) := 'y';

but not

A (3, 4) := 'y';         -- illegal
于 2013-07-09T16:03:23.187 に答える