Hey all! Having a little trouble with my stack. Im trying to print each element that i've pushed onto the stack.
Starting with the stack ctor we know that we have a fixed size for the array. So I allocate the items struct object to hold just that much space:
stack::stack(int capacity)
{
items = new item[capacity];
if ( items == NULL ) {
throw "Cannot Allocoate Sufficient Memmory";
exit(1);
}
maxSize = capacity;
top = -1;
}
yes, items is a struct type of the object "item". Have a look:
class stack
{
stack(int capacity);
~stack(void);
...
private:
int maxSize; // is for the item stack
int top; // is the top of the stack
struct item {
int n;
};
item *items;
public:
friend ostream& operator<<(ostream& out, stack& q)
...
First and formost we want to add to the stack by pushing each incoming element into the array FILO:
bool stack::pushFront( const int n )
{
if ( top >= maxSize-1 )
{
throw "Stack Full On Push";
return false;
}
else
{
++top;
items[top].n = n;
}
return true;
}
// just a textbook example here:
stack::~stack(void)
{
delete [] items;
items = NULL;
maxSize = 0;
top = -1;
}
Yes the real issue for me is the items[++top].n = n; statement. I've been trying to find out how I can drag (+) the items array out to see ALL of the array elements after I push onto the stack.
Im wondering why I cant drag that items[++top].n = n statement out when im debugging. All that comes up is the value that is passed as an 'n' paramater. Do I need to use a stack object type array to store the values into?
When I overload the << operator and try to print the elements I get an insanely large negative number:
ostream& operator<<(ostream& out, stack& q)
{
if ( q.top <= 0 ) // bad check for empty or full node
out << endl << "stack: empty" << endl << endl;
else
for ( int x = 0; x < q.maxSize; x++ )
{
out << q.items[x].n; // try to print elements
}
return out;
}
Im way off and i need some guidence if anyone has the time!
Thanks =)