繁体   English   中英

我正在编写 c++ 代码以使用指针数组实现队列。Memory 分配不正确。有什么建议吗?

[英]I am writing c++ code to implement Queue using pointer array.Memory allocation is not happening correctly.Any suggestion?

这是我使用指针数组进行队列的代码。

#include <iostream>
#include <Queue>

using namespace std;

#define size 2

class Queue{  
public:      
    int f;
    int r;
    int* arr;
public:
    Queue(){
        arr = new int [size];
        int f, r = -1;
    }

    int isEmpty(){
        if(r == -1 && f == -1){
            cout<<"Queue underflow";
        }
        return 0;
    }

    int isFull(){
        if(r == size - 1){
            cout<<"Queue overflow";
        }
        return 0;
    }

    void enqueue(int val){
        if( isFull()){
            cout << "Cannot push element in Queue";
        }
        else{
            arr[r] = val;
            r++;
            cout << "The value in Queue is" << " " << val << endl;
        }
    }

    int dequeue(){
        int a = -1;
        if( isEmpty()){
            cout << "Cannot pop element from Queue";
            return 0;
        }
        else{
            a = arr[f]; 
            f++;
            return a;
        }
    } 
};

int main(){
    Queue q;
    q.f = q.r = 0;
    q.enqueue(1);
    q.enqueue(2);
    q.enqueue(3);
    cout << "Dequeuing element is" << q.dequeue() << endl;
    cout << "Dequeuing element is" << q.dequeue() << endl;
    cout << "Dequeuing element is" << q.dequeue() << endl;
    cout << "Dequeuing element is" << q.dequeue() << endl;
    if( q.isEmpty()){
        cout << "Queue is empty";
    }
    return 0;
}

这是 output

The value in Queue is 1
Queue overflow The value in Queue is 2
The value in Queue is 3
Dequeuing element is1
Dequeuing element is2
Dequeuing element is3
Dequeuing element is563

尽管我在打印一个后仍将大小设置为 2,但它显示“队列溢出”,然后当我将第 4 个元素(尽管没有第四个元素)出列时,它也会打印带有荒谬数字的行。

正如 Nathan Pierson 正确指出的那样,您的函数isFullisEmpty始终返回 0,它在 if 语句中被隐式转换为 false,因此您在enqueuedequeue中的检查不起作用并且函数始终被执行。 另外,我想指出一些其他的事情:

  1. 请不要使用预处理器指令来定义大小变量,而是使用constexpr ( constexpr int size = 2; )。 你选择的名字(size)是很危险的,大部分STL容器都有一个方法也叫size。 然后,您的预处理器指令将用2替换 function 调用,从而破坏编译。
  2. 您的队列 class 中有两个成员变量: rf 他们的意思是什么? 您在方法isFullisEmpty中检查它们,所以我想它们非常重要。 请为变量使用描述性名称(例如使用正面和背面)
  3. 您的方法isFullisEmpty返回 int 以指示真值或假值。 在 C++ 中,有一种特殊的类型用于指示真假: bool 请使用它而不是 int。

暂无
暂无

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

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