如何索引数组指针到数组[队列]?

时间:2019-01-15 11:19:52

标签: c++ arrays pointers

我正在尝试使用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 << "UnderFlow\nProgram Terminated\n";
        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 << "OverFlow\nProgram Terminated\n";
        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 << "UnderFlow\nProgram Terminated\n";
        exit(EXIT_FAILURE);
    }
    return arr[front]; //ERROR HERE
}

1 个答案:

答案 0 :(得分:2)

好吧,它仍然是arr[3][2]

尽管数组不是指针,但由于它们的工作方式和名称的变型,我们使用它们的方式实际上是使用指针。

根据定义,

{x[y] *(x+y)

话虽如此,我建议您删除2D动态分配(这对您的缓存有害),并创建一个大的 Width×Height char s块。您可以使用一些数学运算来为该数据提供2D索引。

您还忘记释放任何内存。如果您使用不错的std::vector来实现我建议的1D数据方案(或者即使您租用了矢量的载体,但是ew!),那么它将为您销毁。当然,如果可以这样做,那么您可能会使用std::queue