C ++ stack implementation
Hey everyone! I have some problems with my stack. I am trying to print every item that I have pushed onto the stack.
Starting at the ctor stack, we know that we have a fixed size for the array. So I allocate a struct of objects to a space like this:
stack::stack(int capacity)
{
items = new item[capacity];
if ( items == NULL ) {
throw "Cannot Allocoate Sufficient Memmory";
exit(1);
}
maxSize = capacity;
top = -1;
}
Yes, elements are the structure type of the element object. Take 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 item into the FILO array:
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 problem for me is [++ top] .n = n; expression. I am trying to figure out how I can drag (+) an array of elements to see ALL the elements of the array after I have pushed onto the stack.
I'm wondering why I can't drag and drop those [++ top] .n = n elements when it's debugged. All that appears is a value that is passed as the "n" parameter. Do I need to use an array of types of stack objects to store values ββin?
When I overload the <operator and try to print the items, 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;
}
I'm leaving and I need some confirmation if anyone has time!
source to share
In the overloaded <statement in a for loop, you are iterating over the maxsize time. But you might as well not push maxsize items onto the stack. You have to repeat the time from above. Also, write a default constructor for the element structure and initialize all variblaes so you don't get garbage values ββwhen you try to print them.
source to share