Guest User

Untitled

a guest
Oct 20th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. #include "DoubleEndedQueue.h"
  2. #include <stdexcept>
  3. #include <iostream>
  4.  
  5. // create new array of size "size" and type "T"
  6. template< class T, int size >
  7. DoubleEndedQueue<T, size>::DoubleEndedQueue() : count(0) {
  8. front = 0;
  9. back = 0;
  10. array = new T[size];
  11. }
  12.  
  13. // check if queue is full
  14. template< class T, int size>
  15. int DoubleEndedQueue<T, size>::full() {
  16. return size == count;
  17. // return front = back;
  18. }
  19.  
  20. // check if queue if empty
  21. template< class T, int size>
  22. int DoubleEndedQueue<T, size>::empty() {
  23. return count == 0;
  24. // return back == (size-1);
  25. }
  26.  
  27. // push element at front of queue if it is not full
  28. // set front to the new position
  29. template< class T, int size>
  30. void DoubleEndedQueue<T, size>::push_front(T const &s) {
  31. if(!full()) {
  32. array[front] = s;
  33. front--;
  34. front = front % size;
  35. count++;
  36. } else std::cout << "DEQ full, push_front failed :(" << std::endl;
  37. }
  38.  
  39. // pop element from front of queue
  40. // set front to new position
  41. // throw runtime_error if deque is empty
  42. template< class T, int size>
  43. T DoubleEndedQueue<T, size>::pop_front() throw(std::runtime_error) {
  44. if(!empty()) {
  45. int tmp = front;
  46. --count;
  47. // front++;
  48. // front = front % size;
  49. if( (front+1) <= (size-1) )
  50. front++;
  51. else
  52. front = 0;
  53. return array[tmp];
  54. } else throw std::runtime_error("Deque is empty, pop_front failed!");
  55. }
  56.  
  57. // pushes element at back of queue
  58. // set back to new position
  59. template< class T, int size>
  60. void DoubleEndedQueue<T, size>::push_back(T const &s) {
  61. if(!full()) {
  62. count++;
  63. array[back] = s;
  64. back++;
  65. back = back % size;
  66. } else std::cout << "DEQ full, push_back failed :(" << std::endl;
  67. }
  68.  
  69. // pop element from back of queue
  70. // set back to new position
  71. // throw runtime_error if deque is empty
  72. template< class T, int size>
  73. T DoubleEndedQueue<T, size>::pop_back() throw(std::runtime_error) {
  74. if(!empty()){
  75. int tmp = back;
  76. --count;
  77. // back--;
  78. // back = back % size;
  79. if ( (back-1) >= 0)
  80. back--;
  81. else
  82. back = size-1;
  83. return array[tmp];
  84. } else throw std::runtime_error("Deque is empty, pop_back failed!");
  85. }
  86.  
  87. // print out all elements
  88. template< class T, int size>
  89. void DoubleEndedQueue<T, size>::print() {
  90. std::cout << "Deque contains: ";
  91. for(int i=0; i<size; i++)
  92. std::cout << array[i] << " - ";
  93. std::cout << std::endl;
  94. }
Add Comment
Please, Sign In to add comment