* Re: Indexing unconstrained arrays
2009-08-30 4:43 Indexing unconstrained arrays Rick
2009-08-30 8:39 ` Pascal Obry
@ 2009-08-31 15:29 ` Adam Beneschan
1 sibling, 0 replies; 3+ messages in thread
From: Adam Beneschan @ 2009-08-31 15:29 UTC (permalink / raw)
On Aug 29, 9:43 pm, Rick <rickdu...@gmail.com> wrote:
> If I have an unconstrained array progressively built from a NULL array
>
> My_Array : Unconstrained_Array_Type (1 .. 0);
>
> to an array of five cells, it should be indexed 1 .. 5. Suppose then
> that I remove cell My_Array (3) by a bit of slicing and splicing.
>
> Does the indexing of the four-cell array that is left run
>
> 1 - 2 - 3 - 4
>
> or does it run
>
> 1 - 2 - 4 - 5 ?
>
We'd need to see your exact code to give an exact answer. But as
you've hopefully figured out by now, you can't really "grow" an array,
in the sense that you can't make an array larger (or smaller) that
you've already declared. (At least not with a simple Ada "array"
type. There are probably ways to use Ada.Containers to achieve
that.) What you can do is to create a new array. So your code that
progressively builds an array may look something like this:
My_Array := new Unconstrained_Array_Type (1 .. 0);
for I in 1 .. Something loop
New_Element := ...;
My_Array := new Unconstrained_Array_Type' (My_Array.all &
New_Element);
end loop;
which progressively adds a New_Element to the end of each array. (The
above wastes a lot of storage, so you need to do a little more to
avoid the wastage, but I'm just trying to demonstrate the basic
concept.)
Now, if My_Array has five elements in the range 1 .. 5, and you do
something like this:
My_Array := new Unconstrained_Array_Type' (My_Array(1..2) &
My_Array(4..5));
The result will be a four-element array. The actual bounds of the
result are given by RM 4.5.3; one of the rules is that if the array
type is unconstrained, and the left operand is not a null array, then
the lower bound of the result is the lower bound of the left operand.
Here, the lower bound of the left operand is 1 (since a slice using
M..N will have bounds M and N), therefore the lower bound of the
result is 1.
The upper bound of the result will then be 4, since the indexes in an
array are always sequential. That is, the indexes of the elements of
the result would be 1, 2, 3, 4. If you want an array with indexes
1-2-4-5, then what you want is an associative array, where array
elements are indexed by a **key** instead of by a simple index. Ada's
basic array type is *not* that kind of array. If you do want
something like that, I think you want one of the "map" types provided
by Ada.Containers.
-- Adam
^ permalink raw reply [flat|nested] 3+ messages in thread