Husi012

ADS Ringbuffer, Fixed array size

Aug 20th, 2022 (edited)
2,156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.65 KB | None | 0 0
  1. class Queue {
  2. private:
  3.     int front;
  4.     int* buffer;
  5.     int capacity;
  6.     int size;
  7. public:
  8.     Queue(int n) : capacity{ n }, front{ 0 }, size{ 0 } {
  9.         buffer = new int[n];
  10.     }
  11.  
  12.     ~Queue() {
  13.         delete[] buffer;
  14.     }
  15.  
  16.     int getSize() {
  17.         return size;
  18.     }
  19.  
  20.     bool isEmpty() {
  21.         return size == 0;
  22.     }
  23.  
  24.     bool isFull() {
  25.         return size == capacity;
  26.     }
  27.  
  28.     void enqueue(int val) {
  29.         if (isFull()) {
  30.             throw "already full";
  31.         }
  32.         buffer[(front + size) % capacity] = val;
  33.         size += 1;
  34.     }
  35.  
  36.     int peek() {
  37.         return buffer[front];
  38.     }
  39.  
  40.     void dequeue() {
  41.         if (isEmpty()) {
  42.             throw "already empty";
  43.         }
  44.         front = (front + 1) % capacity;
  45.         size -= 1;
  46.     }
  47. };
Advertisement
Add Comment
Please, Sign In to add comment