【问题标题】:Circular Array C++圆形数组 C++
【发布时间】:2009-10-29 23:45:58
【问题描述】:

下面的代码是我自己为我的 items 数组实现的 push_front 方法。我想知道是否有人可以帮助我弄清楚如何实现该方法,以便我只是向上或向下移动索引。我需要我的项目留在数组中,而不是将它们转储到“前”变量中:

stack::stack(int capacity) : items(new item[capacity]), maxSize(capacity),
count(0), top(-1)
{
    intFront = 0;
}


bool stack::pushFront(const int nPushFront)
{     
    if ( count == maxSize ) // indicates a full array
    {
        return false;
    }
    for ( int shift = 0; shift < count; )
    {
        if ( shift == top+1 )
        {
            intFront = items[top+1].n;
        }
        items->n = items[++shift].n;
        items[shift].n = intFront;
        if ( shift != maxSize-1 )
        {
            intFront = items[++shift].n;
            items[shift].n = items->n;
        }
    }
    ++count;
    items[top+1].n = nPushFront;

    return true;    
}

items->n 指向的是结构体成员 n,它是一个 int 类型的变量

如您所见,我将数组中的元素移到临时变量中。我的问题是我将如何解决这个问题?我将如何向上或向下移动索引以将项目推到数组的前面?我试图让数组的内容留在数组中..

有什么想法吗?

【问题讨论】:

  • 请重新标记为作业

标签: c++ arrays


【解决方案1】:

您拥有或之前拥有的是stack

我猜你想要的是ring buffer

当您的索引超过数组的末尾时,您将其重置回 0。(它会换行。)当它超过结束索引时,您将该索引设置回开始。您可以在结束索引之后插入元素,只要它不与开始索引重叠。

【讨论】:

  • +1 用于演示在家庭作业环境中正确使用 Internet 资源 :)
猜你喜欢
  • 2012-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
相关资源
最近更新 更多