如何索引指向数组 [queue] 的指针数组
How to index array of pointers to arrays [queue]?
我正在尝试用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
......
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '