#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