fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. const int maxQsize = 100;
  5.  
  6. template < typename T > class Queue {
  7. T q[maxQsize]; // this array holds the queue
  8. int size; // the maximun number of elements that the queue can store
  9. int putloc, getloc; // the put and get indices
  10. public:
  11.  
  12. // Construct a queue of a specific length.
  13. Queue(int len) {
  14. // Queue must be less than max and positive.
  15. if(len > maxQsize) len = maxQsize;
  16. else if(len <= 0) len = 1;
  17.  
  18. size = len;
  19. putloc = getloc = 0;
  20. }
  21.  
  22. // Put a 'T' into the queue.
  23. void put( const T& v ) {
  24. if(putloc == size) {
  25. cout << " -- Queue is full.\n";
  26. return;
  27. }
  28.  
  29. putloc++;
  30. q[putloc] = v ;
  31. }
  32.  
  33. // Get a 'T' from the queue.
  34. T get() {
  35. if(getloc == putloc) {
  36. cout << " -- Queue is empty.\n";
  37. return 0;
  38. }
  39.  
  40. getloc++;
  41. return q[getloc];
  42. }
  43.  
  44. bool empty() const { return getloc == putloc ; }
  45. };
  46.  
  47. // Demonstrate the Queue class.
  48. int main() {
  49.  
  50. Queue<char> charq (100);
  51. const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
  52. for( char c : alphabet ) charq.put(c) ;
  53. while( !charq.empty() ) cout << charq.get() ;
  54. std::cout << '\n' ;
  55.  
  56. Queue<int> intQ(4);
  57. for( int i = 0 ; i < 6 ; ++i ) intQ.put(i) ;
  58. while( !intQ.empty() ) cout << intQ.get() << ' ' ;
  59. std::cout << '\n' ;
  60.  
  61. Queue<double> dblQ(50);
  62. for( int i = 0 ; i < 10 ; ++i ) dblQ.put( i * 1.57 ) ;
  63. while( !dblQ.empty() ) cout << dblQ.get() << ' ' ;
  64. std::cout << '\n' ;
  65. }
  66.  
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
ABCDEFGHIJKLMNOPQRSTUVWXYZ
 -- Queue is full.
 -- Queue is full.
0 1 2 3 
0 1.57 3.14 4.71 6.28 7.85 9.42 10.99 12.56 14.13