Advertisement
jtentor

DemoQueue1 - Queue.h

May 17th, 2020
691
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. //
  2. // Created by Julio Tentor <jtentor@fi.unju.edu.ar>
  3. //
  4.  
  5. #ifndef DEMOQUEUE1_QUEUE_H
  6. #define DEMOQUEUE1_QUEUE_H
  7.  
  8. #include <stdexcept>
  9.  
  10. template <class ELEMENT>
  11. class queue {
  12. public:
  13.     queue(int capacity = 10);
  14.     virtual ~queue();
  15.     void push(const ELEMENT & element);
  16.     ELEMENT front();
  17.     void pop();
  18.     const int size();
  19.  
  20. private:
  21.     int capacity;
  22.     ELEMENT * data;
  23.     int head;
  24.     int tail;
  25.     int count;
  26.     int next(int position);
  27. };
  28.  
  29. template <class ELEMENT>
  30. queue<ELEMENT>::queue(int capacity) {
  31.     this->capacity = capacity;
  32.     this->data = new ELEMENT[this->capacity];
  33.     this->head = 0;
  34.     this->tail = 0;
  35.     this->count = 0;
  36. }
  37.  
  38. template <class ELEMENT>
  39. queue<ELEMENT>::~queue() {
  40.     delete [] this->data;
  41. }
  42.  
  43. template <class ELEMENT>
  44. const int queue<ELEMENT>::size() {
  45.     return this->count;
  46. }
  47.  
  48. template<class ELEMENT>
  49. int queue<ELEMENT>::next(int position) {
  50.     return (++position >= this->capacity)? 0: position;
  51. }
  52.  
  53. template<class ELEMENT>
  54. void queue<ELEMENT>::push(const ELEMENT &element) {
  55.     if (this->count >= this->capacity) {
  56.         throw std::runtime_error("ERROR La cola esta llena...");
  57.     }
  58.     this->data[this->tail] = element;
  59.     this->tail = this->next(this->tail);
  60.     ++this->count;
  61. }
  62.  
  63. template<class ELEMENT>
  64. ELEMENT queue<ELEMENT>::front() {
  65.     if (this->count <= 0) {
  66.         throw std::runtime_error("ERROR La cola esta vacía...");
  67.     }
  68.     return this->data[this->head];
  69. }
  70.  
  71. template<class ELEMENT>
  72. void queue<ELEMENT>::pop() {
  73.     if (this->count <= 0) {
  74.         throw std::runtime_error("ERROR La cola esta vacía...");
  75.     }
  76.     this->head = this->next(this->head);
  77.     --this->count;
  78. }
  79.  
  80. #endif //DEMOQUEUE1_QUEUE_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement