views:

58

answers:

2

Implement a template class named MyStack that creates a stack using STL class vector. MyStack class will have two functions – push() and pop(). Since MyStack is a template class, it must be written in such a way that it can be used to create stack of any type of data (both built-in and custom type). When an element of the stack is popped, it should be deleted from the vector so that the popped data does not use memory any more. In main(), create more than one such stack of different data types, push some sample data, and show the data when they are popped from the respective stack.

A: 

Not going to directly give you the answer. But what you want to do is create a class which holds a pointer of TYPE. When the array that the pointer goes to gets filled copy the info onto a new and larger array then delete the old array. Keep track of the capacity, and the current size.

If you can't program this yourself then you really need to go back and learn more about the language.

BT
That would be reimplementing `std::vector`. He specifically said he's building on `std::vector`.
Potatoswatter
@Potatoswatter - missed that "yay skimming!" - so your solution is better.
BT
+2  A: 

The only way to get a std::vector to shrink is to swap it with a smaller vector. So, freeing the memory of each object as it is popped entails copying (almost) the entire vector for every pop, making it an O(n) operation.

So, I recommend you don't do things that way, or if this is homework, either clearly note why the implementation is so terrible or note that vector::pop_back does not in fact free anything.

By the way, std::stack in <stack> implements O(1) push() and pop() using std::vector to handle allocation.

Potatoswatter