2012-03-13 198 views
1

我是Queue(FIFO)和Qt中的新成员。我想在Qt中创建一个无符号字符数组队列。怎么做?请帮助如何在Qt中创建一个无符号字符数组队列?

unsigned char buffer[1024]; 
+0

你想自己构建队列,还是想使用Qt API进行排队? – 2012-03-13 06:46:41

+0

我喜欢使用Qt API – indira 2012-03-13 07:21:01

回答

3

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

QQueue<unsigned char> queue; 
queue.enqueue(65); 
queue.enqueue(66); 
queue.enqueue(67); 
while (!queue.isEmpty()) 
    cout << queue.dequeue() << endl; 

如果你想建立你自己的队列中,那么我想你可以声明一个Queue类这样的 -

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阵列的队列,那么你将不得不保持队列个指针 -

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]; 

:你这个队列结束,你应该照顾的内存清理。恕我直言,你最好避免这种类型的设计。

+0

但我的要求是Queue中的每个数据应该是一个unsigned char数组。 – indira 2012-03-13 07:15:23

+0

然后你应该使用一个无符号字符指针队列.....请参阅编辑。 – 2012-03-13 08:18:46

+0

非常感谢你的支持 – indira 2012-03-13 09:30:56

相关问题