Thread: Queue with a circular array... nitpick !

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657

    Queue with a circular array... nitpick !

    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;};
    };
        
    }
    Last edited by manasij7479; 10-02-2011 at 04:47 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please ..err..nitpick my code (implementing a stack)
    By manasij7479 in forum C++ Programming
    Replies: 6
    Last Post: 10-04-2011, 05:20 PM
  2. Circular Queue
    By Giridhar Sanjay in forum C++ Programming
    Replies: 6
    Last Post: 07-02-2011, 02:22 PM
  3. Stack and Queue "quack" circular array
    By mrsirpoopsalot in forum C++ Programming
    Replies: 15
    Last Post: 10-20-2009, 03:16 PM
  4. Circular array
    By Opel_Corsa in forum C++ Programming
    Replies: 5
    Last Post: 02-16-2006, 04:15 PM
  5. circular queue
    By strotee76 in forum C++ Programming
    Replies: 2
    Last Post: 05-24-2004, 09:55 AM