Another one... Works fine(at least on my test cases); but .. for a second opinion.
Is there a better way to represent the [warping / wrapping (not sure which!)] of the queue ?
(Press Ctrl+W or Alt+F4 or the Big Red Button if terribly annoyed at these posts :P )
Code: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;}; }; }



1Likes
LinkBack URL
About LinkBacks



