【问题标题】:Expandable Queue in c++c++中的可扩展队列
【发布时间】:2017-09-29 23:39:24
【问题描述】:

在我的家庭作业中,我被要求在 C++ 中实现一个可扩展队列。我们得到了一个无法更改的头文件。头文件有一个动态数组,_front,_size(当前队列中的元素个数)和_capacity。

如果我们尝试将“超出范围”或大于容量的元素推送到队列中,则会要求我们创建一个新队列,其容量是旧队列的两倍。我应该如何在没有指向 next 或 _rear 变量的情况下实现出队和入队?

任何形式的提示都会有所帮助,而不是寻找完整的解决方案。

【问题讨论】:

  • 好吧,如果你有一个数组和一个大小/容量,那么是什么阻止你使用arr + sz - 1 获取指向最后一项的指针或arr + 1 获取下一项的指针?
  • @scohe001 你能解释一下吗?
  • 你确实有一个 _rear 变量 - 它是 _size
  • 当您需要扩展时,分配一个两倍于您容量的缓冲区,将旧数组中的项目复制过来,交换指针,然后删除旧的较小缓冲区。
  • 尽管看起来很诱人,但不要使用realloc。如果你对物体进行操作,它可能会以一些奇怪而有趣的方式咬你。

标签: c++ arrays queue


【解决方案1】:

你必须知道队列的数据类型,假设它是一个整数。然后您可以使用给定的信息(假设您无法按照您的说明编辑头文件并且只能访问少数项目):

头文件

class Queue
{
public:
  Queue()
  {
    _front = new int[10];
    _size = 0;
    _capacity = 10;
  }
  ~Queue()
  {
    delete[] _front;
  }

  int* _front;
  int _size;
  int _capacity;
};

然后您可以在您的代码中执行类似的操作(注意:这未经测试):

#include "Queue.h"

void add(Queue*q, int i)
{
  // If there is room then add it.
  if(q->_size < q->_capacity)
  {
    q->_size++;
    *(q->_front + q->_size - 1) = i;
  }
  else
  {
    // If full then create a new array.
    int* arr = new int[q->_capacity * 2];

    // Copy over the old data.
    for(int j = 0; j < q->_capacity; j++)
    {
      *(arr + j) = *(q->_front + j);
    }

    q->_capacity *= 2;   // Update parameter.
    delete[] q->_front;  // Delete memory.
    q->front = arr;      // Point to new array.
    arr = nullptr;       // c++11

    q->_size++;          // Same as above when there was room.
    *(q->_front + q->_size - 1) = i;
  }
}

int main()
{
   Queue q;

   add(&q, 1234);   
}

如果您可以在头文件中添加函数,那就更好了。因为我不知道你可以做什么的限制,所以我创建了一个外部函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2023-03-17
    • 2017-10-25
    相关资源
    最近更新 更多