Bounded stack of integers C++
Hey, just doing some revision for upcoming exams and i'm looking at a past paper.
I'm asked to write the class implementation for this:
class Stack
{
public:
Stack(int n=1);
int pop();
void push(int);
int isEmpty();
int isFull();
˜Stack();
private:
int top; // index of element at top of stack
int size; // maximum number of elements storable
int * cell; // pointer to elements stored in stack
};
I understand the theory of sta开发者_开发百科cks and i know what the methods have to do, the bit that confuses me is where are the integers that are passed to the stack stored, and how is this done? Maybe im missing something realy simple but im stumped?
I'd guess that your int * cell
is the clue, it is a pointer into an array, so you'd initialize it as such int * cell = new int[size];
Now you can use cell
as an index into your dynamic array.
I wouldn't have named it that, or likely implemented it in this fashion, but the int * cell
is where your items go. I assume they want you to initialize it to an array of size
when the stack is instantiated.
The integers are stored on the heap, and the 'bottom' element is stored at
Stack s(5);
s.cell[0];
The second at
s.cell[1];
and so on.
精彩评论