繁体   English   中英

圆数组C ++

[英]Circular Array C++

下面的代码是我自己的实现,用于我的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类型的变量

如您所见,即时消息将元素从数组中移出了临时变量。 我的问题是我该如何解决? 我将如何上下移动索引以将项目推到数组的前面? 我试图获取数组的内容以保留在数组中。

有什么想法吗?

您在那里或之前曾经拥有的是一堆

我想您想要的是一个环形缓冲区

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM