Reputation: 595
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?
Upvotes: 3
Views: 2095
Reputation: 595
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
Upvotes: 5
Reputation: 205775
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.
Upvotes: 5
Reputation: 8522
Presumably you know how to initially allocate the (empty) array for your stack.
When you need to reallocate to a larger array, allocate it into a local access variable, akin to "st" in your C++ example. Then loop though the existing, full array, copying its elements into your newly allocated one.
Free, using an instantiation of Unchecked Deallocation, the old array--that's the Elements field in your Vector record. Then set the Elements field to the variable containing the newly allocated array.
Essentially, it closely follows your C++ example, only you don't need to mess around with sizeof() and you use a copy loop instep of memset/memcpy.
Upvotes: 4