tags:

views:

85

answers:

2

Im tryin to implement a push front method to a C++ double ended queue. The way that i did it was shifting each element of the array. It worked, but my program crashes at the end! In my push front method I seem to be "running past the end of my array", resulting in a heap corruption error, debug assertion, those things..

I havent been able to develop a push_front implementation without shifting the array.

stack::stack(capacity) : items(new item[capacity]), front(*items), maxSize(capacity-1)
{
    top = -1;
}

bool stack::pushFront(const int nPushFront)
{     
        if ( count == maxSize ) // indicates a full array
        {
            return false;
        }
        for ( int entry_int = 0; entry_int < count; ) // loop less than however many we count.
        {
            if ( entry_int == top+1 )
            {
                front.n = items[top+1].n;
            }
            items->n = items[++entry_int].n;
            items[entry_int].n  = front.n;
            front.n = items[++entry_int].n;
            items[entry_int].n  = items->n;
        }
        ++count;
        items[top+1].n = nPushFront;
        return true;    
}

can anyone help?

+2  A: 

This is easy to do without shifting by keeping both front and back offsets/pointers. Take a look at boost circular buffer for example.

Nikolai N Fetissov
Well, I titled this as the "user implementation" of a push_front method, like im doing it without the use of boost, stl, and the like.
still a circular buffer avoids shifting all elements on each push_front call. without using boost, Nikolai is pointing you to a reference implementation you can read: a circular buffer is a standard implementation of a double-queue, which you should try to implement only because it is a good exercise.
Adrien Plisson
A: 

bool Stack::PushFront (const int nElement) {

  if(count == maxSize) return false;

  for(int i = count ; i > 0; i--) 
  {
      items[i].n = items[i-1].n;
  }   

  item[top+1].n = nElement; 
  count++;      
  return true;

}

Ashish