adagnatgnat-gpsada2012

How do you implement Generic_Sorting in Ada for a vector?


I'm trying to do some basic translations of old C++ code from many moons ago to learn Ada, and I have been absolutely stumped on how to sort a vector using the built-in Generic_Sorting. I haven't been able to find any concrete examples of it in action, the closest being a now-defunct Danish wiki article which looks like it would have had a full example but the archive didn't snatch it up: https://web.archive.org/web/20100222010428/http://wiki.ada-dk.org/index.php/Ada.Containers.Vectors#Vectors.Generic_Sorting

Here is the code as I thought it should work from the above link:

with Ada.Integer_Text_IO;    use Ada.Integer_Text_IO;
with Ada.Strings.Unbounded;  use Ada.Strings.Unbounded;
with Ada.Containers.Vectors; use Ada.Containers;

procedure Vectortest is
   package IntegerVector is new Vectors
     (Index_Type   => Natural,
      Element_Type => Integer);
   package IVSorter is new Generic_Sorting;

   IntVec : IntegerVector.Vector;
   Cursor : IntegerVector.Cursor;
begin
   IntVec.Append(3);
   IntVec.Append(43);
   IntVec.Append(34);
   IntVec.Append(8);

   IVSorter.Sort(Container => IntVec);

   Cursor := IntegerVector.First(Input);
   while IntegerVector.Has_Element(Cursor) loop
      Put(IntegerVector.Element(Cursor));
      IntegerVector.Next(Cursor);
   end loop;

end Vectortest;

I've tried so many different combinations of use and with but all I can get are various error codes. The above code gives Generic_Sorting is not visible, but when I try to explicitly state with Ada.Containers.Vectors.Generic_Sorting I get the error "Ada.Containers.Vectors.Generic_Sorting" is not a predefined library unit. I have no idea what I'm doing wrong here, I'm sure it's a fundamental misunderstanding of the way Ada brings in packages, and I hope that nailing this down will help me understand it a bit better.


Solution

  • Generic_Sorting is an inner package to Ada.Containers.Vectors and cannot be explicitly withed (as you have discovered). And since Ada.Containers.Vectors is itself a generic package, Generic_Sorting is an inner package to the instantiation of Ada.Containers.Vectors. So you can reach it by prefixing with the name of the instance:

    package IVSorter is new IntegerVector.Generic_Sorting;