Any better 'logic' to implement a contiguous queue circularly ?
Here is my implementation, of a queue with a circular array.
Cookies for anyone finding faults in it or suggesting better ways to do something.
(I know that the exception handling can be done better, but this code isn't going to be used in a program, the STL has seen to that!)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
namespace mm
{
enum queue_error{overflow, underflow, beheaded};
template<typename T, int Size>
class queue
{
private:
T mem[Size];
int head_ptr;
int tail_ptr;
inline int diff(int pt1, int pt2) {return pt1-pt2 >=0 ? pt1-pt2 : pt1+Size-pt2 ;}
// pt1 - pt2 .. keeping 'circular' logic in mind
inline void increment(int& ptr) { ptr++; ptr%=Size; };
// incrementing, and wrapping around when necessary
public:
queue():head_ptr(1),tail_ptr(0){};
void push(const T& in)
{
if(this->full()) throw(overflow);
increment(tail_ptr);
mem[tail_ptr] = in ;
};
void pop()
{
if(this->empty()) throw(underflow);
increment(head_ptr);
};
T& head()
{
if(this->empty())throw(beheaded);
return mem[head_ptr];
};
int size()
{
if(this->empty())return 0;
else return diff(tail_ptr,head_ptr)+1;
};
bool empty(){return diff(head_ptr,tail_ptr)==1;};
bool full(){return diff(head_ptr,tail_ptr) ==2;};
};
}
|
Last edited on
Topic archived. No new replies allowed.