【问题标题】:Implementation of Queue using Arrays in C++在 C++ 中使用数组实现队列
【发布时间】:2020-09-01 15:36:14
【问题描述】:

我已经编写了这段代码,但对它为什么显示分段错误感到困惑。我认为我的动态内存分配在这里给我带来了问题。谁能告诉我是什么导致了这里的分段错误以及如何改进代码。

另外,请告诉我是否可以使用 ClassName obj(); 创建对象并将其存储在堆栈而不是堆中。或者在某些问题中是否需要此实现

#include<bits/stdc++.h>
using namespace std;

class Queue
{
public:
    int rear, front, size,capacity;
    int* arr;
     
    Queue(int c)
    {
        capacity=c;
        rear=c-1;
        front=0;
        int *arr= new int[c*sizeof(int)];
    }
};


int isEmpty(Queue* queue)
{
    return (queue->size==0);
}

int isFull(Queue* queue)
{
    return (queue->size==queue->capacity);
}


void enqueue(Queue* queue, int x)
{

    if(isFull(queue))
        return;
    queue->rear=(queue->rear+1)%queue->capacity;
    queue->arr[queue->rear]=x;
    queue->size+=1;
}

int dequeue (Queue* queue)
{
    
    if(isEmpty(queue))
        return 0;
     int x = queue->arr[queue->front];
    queue->front= (queue->front+1)%queue->capacity;
   
    queue->size-=1;
}

int front (Queue* queue)
{

    if(isEmpty(queue))
        return 0;
    return queue->arr[queue->front];
}

int rear (Queue* queue)
{
    if(isEmpty(queue))
    return INT_MIN;
    return queue->arr[queue->rear];
}

int main()
{
    Queue* queue=new Queue();

    enqueue(queue,10);
    enqueue(queue,20);
    enqueue(queue,30);
    enqueue(queue,40); 
  
    cout << "Front item is "
         << front(queue) << endl; 
    cout << "Rear item is "
         << rear(queue) << endl; 
}

【问题讨论】:

  • I got compilation error 而不是分段错误。
  • 您能告诉我这是什么原因吗?我怀疑我对Queue的动态分配感觉。
  • 请不要混淆您的代码的不同版本/每个问题只问一个问题。我想Queue* queue=new Queue(); 是您稍后添加的,只是没有出现分段错误。发布的代码不可能出现段错误
  • 对了,为什么将处理队列的函数声明为依赖函数而不是Queue的成员函数?
  • Queue queue = new Queue(); 一直都在那里,我遇到了段错误。刚刚尝试再次运行,它显示相同的内容。

标签: c++ arrays queue c++14 c++17


【解决方案1】:

您的代码至少有 3 个问题:

首先,

Queue* queue=new Queue();

将导致编译错误,因为没有定义默认构造函数,而在类Queue中定义了另一个构造函数。

要解决此问题,您应该执行以下操作之一:

  • 更改此行以匹配定义的构造函数,例如Queue* queue=new Queue(1024);
  • 将默认构造函数添加到类Queue
  • 为类Queue的构造函数添加参数c的默认值,如Queue(int c = 1024)

其次,函数dequeue有一个执行路径,在该路径中执行到达函数末尾而不执行任何return语句。

看来return x;应该加在函数末尾。

三是行

int *arr= new int[c*sizeof(int)];

不好,因为:

  • 这存储指向将在此构造函数结束时消失的局部变量的指针,而不是成员变量。
  • 您不需要乘以 sizeof(int),因为指定的是要分配的元素数,而不是字节数。

该行应该是

arr= new int[c];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多