Ada Vectors : The simplest container

This example shows how Ada language handles generic containers vector ( C++ uses std::vector,java uses ArrayList). The most basic containers is Ada.Containers.Vectors that provides a resizable array and then sorting fonction. More info here


One can declare an array :

 A : array (1 .. 20) of Natural;

However, array data struct size is provided at initialisation and can not be change. Hence, one could prefer the use of Ada.Containers.Vectors that may change size if needed :

package VectInt is new Ada.Containers.Vectors(Index_Type   => Natural, Element_Type => Natural);
 V : VectInt.Vector;

One can add data to this container :

 V.Append ( 10 );
 V.Prepend ( 10 );

One can iterate over it. There are two option , the traditional index based one and the "for .. of Container" method.

for I in V.First_Index .. V.Last_Index loop
   Ada.Text_IO.Put_Line (" element " & V.Element (Indx)'Img);
end loop;
for E of V loop
      Ada.Text_IO.Put_Line (" element " & E'Img);
end loop;

More information are available : First Element, Last_Element, Capacity and Length ( All those features are provided is the same way in C++ , Java , ... ) .

Put_Line ("Vector has "  & V.Length'Img & " elements\;
Put_Line ("First element is now " & Img (V.First_Element));
Put_Line ("Last element is now " & Img (V.Last_Element));

Cursor concept ( called iterator for java and C++ ) are available too.

declare
C : Cursor := V.First
begin
   while C /= No_Element loop
      C := Next (C);
   end loop;
  end;
 

Swap can be used to change order elements

V.Swap (V.First, V.Last);

Sorting element is also a widespread operation available for Vector. It requires the ordering fonction and then the instanciation of a new package from Ada.Containers.Vectors.Generic_Sorting.


with Ada.Text_IO;
with Ada.Containers.Vectors;
 
procedure Main is
   package VectInt is new Ada.Containers.Vectors
     (Index_Type   => Natural,
      Element_Type => Natural);
 
   function isLower (Left, Right : Natural) return Boolean is
   begin
 
      return Left < Right;
   end isLower;
   function isUpper (Left, Right : Natural) return Boolean is
   begin
 
      return Left > Right;
   end isUpper;
 
   package Sorter1 is new VectInt.Generic_Sorting ("<" => isLower);
   package Sorter2 is new VectInt.Generic_Sorting ("<" => isUpper);
   T : VectInt.Vector;
 
begin
 
 
   for I in 1 .. 100 loop
      VectInt.Append (T, I * I);
      Ada.Text_IO.Put_Line ("Append   :" & I'Img);
      Ada.Text_IO.Put_Line ("Capacity :" & VectInt.Capacity (T)'Img);
   end loop;
   Ada.Text_IO.Put_Line (" Sorter1");
   Sorter1.Sort (Container => T);
   for Indx in T.First_Index .. T.Last_Index loop
      Ada.Text_IO.Put_Line (" element " & T.Element (Indx)'Img);
   end loop;
   Ada.Text_IO.Put_Line (" Sorter2");
   Sorter2.Sort (Container => T);
   for Indx in T.First_Index .. T.Last_Index loop
      Ada.Text_IO.Put_Line (" element " & T.Element (Indx)'Img);
   end loop;
 
end Main;