Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ada - Dynamically reallocate array

I'm trying to write a stack based on array, that can be dynamically reallocated. The main problem I have is how to implement procedure that resizes the array. In C++ it could look like that:

template<class T, int incr>
void Vector<T, incr>::inflate(int increase) {
    const int tsz = sizeof(T*);
    T** st = new T*[quantity + increase];
    memset(st, 0, (quantity + increase) * tsz);
    memcpy(st, storage, quantity * tsz);
    quantity += increase;
    delete []storage;
    storage = st;
}

where int quantity; and T** storage; are declared in private section.

If there is anyone who could share me some sample I'd be much grateful. I tried to look through the implementation of Ada.Containers.Vectors but argh... it's to big =P

So far I've made this Vector.ads Can anyone help?

like image 437
thim Avatar asked Sep 04 '26 14:09

thim


2 Answers

If you go with Ada.Containers.Vectors, there's a helpful discussion in the Rationale for Ada 2005: §8.2 Lists and vectors. Basically, you instantiate the generic package with your Index_Type and Element_Type:

package Container is new Containers.Vectors (Natural, T);

Then declare a variable having the new type:

Stack : Container.Vector;

The Push procedure then becomes Stack.Append and the Pop function returns Stack.Last_Element. Note the availability of prefixed notation.

like image 82
trashgod Avatar answered Sep 06 '26 10:09

trashgod


Ok, case is solved. I've finished my Vector class (which is actually a stack build on an array). Thank everyone for help.

Just for posterity here is my code. Hope someone will learn something from it. Code -> https://gist.github.com/496a50bc7f5cd93f8d91

If you'd like to take a look and find something worth changing just comment. ;D

like image 41
thim Avatar answered Sep 06 '26 09:09

thim