如何索引指向数组 [queue] 的指针数组

How to index array of pointers to arrays [queue]?

本文关键字:数组 queue 指针 何索引 索引      更新时间:2023-10-16

我正在尝试用C++数组编程一个队列。

我使用了这种方法 https://stackoverflow.com/a/936709/7104310 如下所示。

我的问题:如何索引数组以填充它们?

例如,在正常的 2D 数组中,它将是 arr[3][2]。但是我不知道如何使用指针来做到这一点。问题帽在解决方案中未得到回答。

谢谢!

#include <iostream>
#define MAX_SIZE 3
using namespace std;

// ary[i][j] is then rewritten as
//arr[rear*capacity + front]
// Class for queue
class msg_queue
{
    char **arr;     // array to store queue elements
    int capacity;   // maximum capacity of the queue
    int front;      // front points to front element in the queue (if any)
    int rear;       // rear points to last element in the queue
    int count;      // current size of the queue
public:
    msg_queue(int size = MAX_SIZE, int slot_length = MAX_SIZE);     // constructor
    void dequeue();
    void enqueue(char x);
    char peek();
    int size();
    bool isEmpty();
    bool isFull();
};
// Constructor to initialize queue
msg_queue::msg_queue(int size, int slot_length)
{
    arr = new char*[size];
    for (int i = 0; i < size; ++i) {
        arr[i] = new char[slot_length];
    }
    capacity = size;
    front = 0;
    rear = -1;
    count = 0;
}
// Utility function to remove front element from the queue
void msg_queue::dequeue()
{
    // check for queue underflow
    if (isEmpty())
    {
        cout << "UnderFlownProgram Terminatedn";
        exit(EXIT_FAILURE);
    }
    cout << "Removing " << arr[front] << 'n';
    front = (front + 1) % capacity;
    count--;
}
// Utility function to add an item to the queue
void msg_queue::enqueue(char item)
{
    // check for queue overflow
    if (isFull())
    {
        cout << "OverFlownProgram Terminatedn";
        exit(EXIT_FAILURE);
    }
    cout << "Inserting " << item << 'n';
    rear = (rear + 1) % capacity;
    arr[rear] = item;  //ERROR HERE
    count++;
}
// Utility function to return front element in the queue
char msg_queue::peek()
{
    if (isEmpty())
    {
        cout << "UnderFlownProgram Terminatedn";
        exit(EXIT_FAILURE);
    }
    return arr[front]; //ERROR HERE
}

嗯,它仍然arr[3][2].

虽然数组不是指针,但我们使用它们的方式实际上是使用指针,因为它们的工作方式和名称衰减的方式。

根据定义,x[y]*(x+y)的。

话虽如此,我建议您放弃 2D 动态分配(这对您的缓存来说是毒药),而是创建一个大块的宽度×高度char s。您可以使用一些数学来提供该数据的 2D 索引。

你也忘了释放任何记忆。如果你使用一个不错的std::vector来实现我建议的一维数据方案(或者即使你雇佣了一个向量向量,但是哇!),那么它就会为你被破坏。当然,如果你能做到这一点,那么你可能会使用std::queue......