Implementing FIFO queues with arrays

Source: Internet
Author: User

#include <iostream>using std::cout;using std::endl;using std::string;// queue  Implemented as an arraytemplate<class t, int size = 100>class  arrayqueue {public:    arrayqueue ()  {          first = last = -1;     }     void enqueue (T);     t dequeue ();     bool isfull ()   {         return first == 0 & & last == size-1 | |  first == last + 1;     }    bool  IsEmpty ()  {         return first == -1;      }private:    int first; // poiNt to the first element that can be take away from the  queue.    int last; // point to the last element  that was put into the queue recently.    T  Storage[size];}; Template<class t, int size>void arrayqueue<t,size>::enqueue (T el)  {    if  (!isfull ())         if  (last ==  size-1 | | &NBSP;LAST&NBSP;==&NBSP;-1)  {             storage[0] = el;            last =  0;            if  (first == -1 )                 first = 0;        }         else storage[++last] = el;   else cout <<  "full  Queue.\n ";}  Please do check  "!ifempty ()"  before invoke this api, else  a SIGSEGV error will happen.template<class T, int size>T  Arrayqueue<t,size>::d equeue ()  {       T tmp;     tmp = storage[first];    if  (first == last)           last = first = -1;     else if  (first == size-1)          first  = 0;    else first++;    return tmp;} Int main () {    arrayqueue<string, 5> strarray;    strarray.enqueue ("what ");     strarray.enqueue ("is ");     strarray.enqueue ("your ");     strarray.enqueue ("name? ");     strarray.enqueue ("I ");     strarray.enqueue ("am ");     strarray.enqueue ("Frank.");     while (!strarray.isempty ()) {        cout  << strarray.dequeue ();     }    cout << endl ;         // when queue is empty, dequeue ()  will cause segmentation fault.    //cout <<  Strarray.dequeue ();     return 0;}


This article from the "write articles in C + +" blog, declined reproduced!

Implementing FIFO queues with arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.