首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Qt中创建无符号数组队列?

如何在Qt中创建无符号数组队列?
EN

Stack Overflow用户
提问于 2012-03-13 14:14:03
回答 1查看 6.1K关注 0票数 1

我是队列(FIFO)和Qt的新手。我想在Qt中创建一个无符号字符数组队列。该怎么做呢?请帮帮忙

代码语言:javascript
复制
unsigned char buffer[1024];
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-13 14:49:35

如果你想使用Qt,那么你可以使用QQueue类-

代码语言:javascript
复制
 QQueue<unsigned char> queue;
 queue.enqueue(65);
 queue.enqueue(66);
 queue.enqueue(67);
 while (!queue.isEmpty())
     cout << queue.dequeue() << endl;

如果您想自己构建队列,那么我想您可以像这样声明一个Queue类-

代码语言:javascript
复制
class Queue
{
private:
    enum{SIZE=1024, EMPTY=0};
    unsigned char buffer[SIZE];
    int readHead, writeHead;

public:
    Queue()
    {
        readHead = writeHead = EMPTY;
    }

    void push(unsigned char data);
    unsigned char pop();
    unsigned char peek();
    bool isEmpty();
};

void Queue::push(unsigned char data)
{
    if((readHead - writeHead) >= SIZE)
    {
        // You should handle Queue overflow the way you want here.
        return;
    }

    buffer[writeHead++ % SIZE] = data;
}

unsigned char Queue::pop()
{
    unsigned char item = peek();
    readHead++;
    return item;
}

unsigned char Queue::peek()
{
    if(isEmpty())
    {
        // You should handle Queue underflow the way you want here.
        return;
    }

    return buffer[readHead % SIZE];
}

bool Queue::isEmpty()
{
    return (readHead == writeHead);
}    

如果您想维护一个unsigned char数组队列,那么您必须维护一个unsigned char指针队列-

代码语言:javascript
复制
QQueue<unsigned char *> queue;
unsigned char *array1 = new unsigned char[10];    // array of 10 items
array1[0] = 65;
array1[1] = 66;
queue.enqueue(array1);
unsigned char *array2 = new unsigned char[20];    // an array of 20 items
queue.enqueue(array2);

unsigned char *arr = queue.dequeue();
qDebug() << arr[0] << ", " << arr[1];

注意::在处理完这个队列之后,您应该注意内存清理。不过,你最好避免这种类型的设计。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9679188

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档