### Circular queue size, help me please !!

Dear all,
I am implementing a circular queue, but I can't find the formula to obtain the size of the queue; this one doesn't work correctly and gives me wrong results:

int size = abs (m_tail - m_front) ;

where m_front and m_tail are the indexes of the queue's front and tail respectively.

can you show the code?

EDIT:

This worked for me. very similar:
 ``123456789101112131415161718`` ``````#include using namespace std; int main() { int absolute; int first,last; cout<<"Enter a big number: "; cin>>first; cout<<"Enter another one(smaller): "; cin>>last; absolute=abs(first-last); cout<<"Absolute: "<
Last edited on
Thanks for the reply. Here the class Circular_Queue as I have implemented:
 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107`` `````` #include "circular_queue.h" #include #include #define MaxSize 150000 // in bytes, which means 100 packets maximum using namespace std ; typedef unsigned char Byte ; CircularQueue::CircularQueue() { m_front = 0 ; m_tail = 0 ; } CircularQueue::~CircularQueue() { } void CircularQueue::insert(Byte byte) { if (m_front == (m_tail + 1) % MaxSize) { // cout << "Circular Queue is full" << endl ; } else { m_tail = (m_tail + 1) % MaxSize ; m_array[m_tail] = byte ; } } Byte CircularQueue::dequeue(void) { Byte byte ; if (m_front == m_tail) { //cout << "the circular queue is empty" << endl ; } else { byte = m_array[m_front] ; m_front = (m_front + 1) % MaxSize ; } return byte ; } int CircularQueue::Size(void) { int size = abs(m_front – m_tail) ; return size ; } bool CircularQueue::isEmpty(void) { if (m_front == m_tail) return true ; else return false ; } bool CircularQueue::isFull(void) { if ((m_front == m_tail + 1) % MaxSize) return true ; else return false ; } ``````

I have a problem with the function Size() which gives me a wrong result. Is there a general formula to get the circular queue size? Thanks in advance
Thank you for the code snippet but it doesn't seem to be the same case since what you are implementing is not a circular queue. By definition, in a circular queue, the front and tail indexes are set to zero when they reach the max_size , which is expressed here by a modulo. May be I don't explain my problem correctly but your code does simply calculate the difference between two numbers and shows the result, doesn' it??
Is circular queue a topic, hahaha lol! I'm still learning not a pro at all. but I do my best to help!
`int size = abs (m_tail - m_front) ;` ¿why do you use abs()? ¿when that value could be negative?

By the way
 ``12345`` ``````/* if (m_front == m_tail) return true ; else return false;*/ return m_front == m_tail;``````
Last edited on
Topic archived. No new replies allowed.