fork(1) download
  1. // implementation file for the queue class
  2.  
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. const int queue_size = 6;
  7.  
  8. class queue
  9. {
  10. private:
  11. char data [queue_size]; // elements in the queue
  12. int front, // index to the front of the queue, indexes one previous
  13. // to actual front element (remove)
  14. rear; // index of the rear element;
  15. public:
  16. queue (); // create an empty queue
  17. void enqueue (char item); // adds an element to the rear
  18. char dequeue (); // removes an element from the front
  19. bool empty (); // returns true for an empty queue
  20. bool full (); // returns true for a full queue
  21. int elements (); // returns the number of elements in the queue
  22. void print (); // prints the queue from front to rear
  23. };
  24.  
  25. // returns the number of elements in the queue. If queue is empty, it returns 0.
  26. int queue::elements ()
  27. {
  28. int i;
  29. if(empty())
  30. return 0;
  31. else
  32. for (i = front+1; i != (rear + 1) % queue_size; i = (i + 1)%queue_size)
  33. return i;
  34. }
  35.  
  36. // prints the elements in the queue from first to last element. If the queue is empty, nothing
  37. // is printed
  38. void queue::print ()
  39. {
  40. int i;
  41. if(!empty())
  42. for (i = front+1; i != (rear + 1) % queue_size; i = (i + 1)%queue_size)
  43. cout << data[i] << " ";
  44. }
  45.  
  46. // constructor creates an empty queue
  47. queue::queue ()
  48. {
  49. front = 0;
  50. rear = 0;
  51. }
  52.  
  53. // enqueue adds an element to the rear of the queue
  54. void queue::enqueue (char item)
  55. {
  56. // if full, can't add another element
  57. if (full ())
  58. {
  59. cout << "\n\nQueue Error: Can't add to a full queue";
  60. cout << "\nQueue will not be changed";
  61. }
  62. else // ok to add an item
  63. {
  64. rear = (rear + 1) % queue_size;
  65. data [rear] = item;
  66. }
  67. }
  68.  
  69. // dequeue removes an element from the front of the queue
  70. char queue::dequeue ()
  71. {
  72. // if the queue is empty, we can't remove a value
  73. if (empty ())
  74. {
  75. cout << "\n\nQueue Error: Can't remove from an empty queue";
  76. cout << "\nReturning a blank";
  77. return ' ';
  78. }
  79. else // ok to remove a value
  80. {
  81. front = (front + 1) % queue_size;
  82. return data [front];
  83. }
  84. }
  85.  
  86. // empty returns true if the queue is empty
  87. bool queue::empty ()
  88. {
  89. return front == rear;
  90. }
  91.  
  92. // full returns true if the queue is full
  93. bool queue::full ()
  94. {
  95. return (rear + 1) % queue_size == front;
  96. }
  97.  
  98. int main()
  99. {
  100. queue q;
  101. q.enqueue('a');
  102. q.enqueue('b');
  103. q.enqueue('c');
  104. q.enqueue('d');
  105. q.enqueue('e');
  106. q.print();
  107. }
  108.  
Success #stdin #stdout 0s 3140KB
stdin
Standard input is empty
stdout
a b c d e