push_front C++ user implementation
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 = nPushFr开发者_开发技巧ont;
return true;
}
can anyone help?
This is easy to do without shifting by keeping both front and back offsets/pointers. Take a look at boost circular buffer for example.
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;
}
精彩评论