tags:

views:

248

answers:

3

Hey all! Thought I'd post anotherhomework question if thats alright :x

What I want to happen is for the pushFront(int) function to do this:

bool stack::pushFront( const int n )
{
items[++top] = n;  // where top is the top of the stack
return true; // only return true when the push is successful
}

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;    

i've defined the ctor to the stack class object and dtor as follows:

stack::stack(int capacity)
{   
    items = new item[capacity];

    if ( items == NULL ) {
      throw "Cannot Allocoate Sufficient Memmory";
      exit(1); 
    }
    maxSize = capacity;
    top  = -1;
}

stack::~stack(void)
{
    delete [] items;

    items  = NULL;
    maxSize  = 0;
    top   = -1;
}

Yes the main issue for me is the items[++top] = n; statement. I've been trying to find ways around it like below:


bool stack::pushFront(const int n)
{
    int *a = new int[maxSize];
    a[++top] = n;

    return true;
}

But I cant drag (+) 'a' array out to see those actual array elements... Which is what I was hoping to happen..

What I want is for the statement items[++top] = n; to work..

A: 

It appears you have defined a stack of fixed size. You should check that adding to the stack does not exceed the size. To pushFront, you just need to copy the data in the array to make space for the 0th element to be modified:


bool stack::push(const int n)
{
    if ( top >= capacity-1 ) return false;
    items[++top].n = n
}

bool stack::pushFront(const int n)
{
    if ( top >= capacity-1 ) return false;
    bcopy( items, items+1, top+1 );
    items[0].n = n;
    return true;
}
Timothy Pratley
actually, the statement items[++top] = n; within the body of the bool stack::pushFront( const int n) function, is invalid and i recieve this error: error C2679: binary '=' : no operator found which takes a right-hand operand of type 'const int' (or there is no acceptable conversion). Followed by: could be 'stack::item ?
everywhere I use items as an array assigned to n, i get an error :/
As Geerad pointed out it should be:items[++top].n = n;because items is a structure.
Timothy Pratley
what is bcopy in your code?
+2  A: 

You can't assign an int value to an item, because you haven't told the compiler how to do that.

You need to either write a constructor or operator= for item that takes an int as a parameter or use

items[++top].n = n;
Geerad
A: 

bool stack::pushFront( const int n ) {

if(top == maxSize-1) return false;

items[++top].n = n; // where top is the top of the stack

return true; // only return true when the push is successful

}

GG