2009-10-29 52 views
0

Im试着实现一个推送前端方法到C++双端队列。我做这件事的方式是移动数组中的每个元素。它工作,但我的程序最终崩溃!在我的推前台方法中,我似乎“跑过我的阵列的末尾”,导致堆损坏错误,调试断言,这些事情..push_front C++用户实现

我还没有能够开发push_front实现而不移动数组。

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;  
} 

任何人都可以帮忙吗?

+0

我aplogize的格式,所以我张贴之前看起来很好。 – user40120 2009-10-29 21:03:24

+0

随时修复它 – 2009-10-29 21:17:18

+0

发布前删除标签。 – 2009-10-29 21:36:59

回答

2

通过保持正面和背面的偏移量/指针,这很容易做到不移位。以boost circular buffer为例。

+0

好吧,我把它称为push_front方法的“用户实现”,就像我在不使用boost,stl等的情况下做的那样。 – user40120 2009-10-29 21:08:39

+3

仍然是一个循环缓冲区,避免了在每个push_front调用中移动所有元素。在不使用boost的情况下,Nikolai正在向您指出一个您可以阅读的参考实现:循环缓冲区是双队列的标准实现,您应该尝试实施,因为这是一个很好的练习。 – 2009-10-29 21:16:20

0

BOOL堆栈:: 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; 

}