1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
#include <iostream> #include <vector> class Queue { private: std::vector<int> data; int frontIndex; int rearIndex; public: // Constructor to initialize the queue Queue() : frontIndex(0), rearIndex(0) {} // Method to add an element to the queue void enqueue(int value) { data.push_back(value); rearIndex++; } // Method to remove and return the front element from the queue int dequeue() { if (isEmpty()) { throw std::out_of_range("Queue is empty"); } int value = data[frontIndex]; frontIndex++; return value; } // Method to get the front element without removing it int front() const { if (isEmpty()) { throw std::out_of_range("Queue is empty"); } return data[frontIndex]; } // Method to check if the queue is empty bool isEmpty() const { return frontIndex == rearIndex; } // Method to get the size of the queue int size() const { return rearIndex - frontIndex; } }; int main() { Queue q; // Enqueue elements into the queue q.enqueue(10); q.enqueue(20); q.enqueue(30); q.enqueue(40); std::cout << "Front element: " << q.front() << std::endl; // Dequeue elements from the queue std::cout << "Dequeued: " << q.dequeue() << std::endl; std::cout << "Dequeued: " << q.dequeue() << std::endl; std::cout << "Front element after dequeuing: " << q.front() << std::endl; std::cout << "Queue size: " << q.size() << std::endl; return 0; } |
Explanation
- Queue Class:
- The
Queue
class is implemented using astd::vector<int>
to store the elements. - It maintains two indices:
frontIndex
andrearIndex
, which represent the positions of the front and rear elements in the queue.
Advertisement - The
- Enqueue Operation:
- The
enqueue(int value)
AdvertisementrearIndex
.
- The
- Dequeue Operation:
- The
dequeue()
method removes and returns the element at the front of the queue by accessing the element atfrontIndex
and then incrementsfrontIndex
. If the queue is empty, it throws an exception.
- The
- Front Operation:
- The
front()
method returns the element at the front of the queue without removing it. If the queue is empty, it throws an exception.
Advertisement - The
- isEmpty Operation:
- The
isEmpty()
method checks if the queue is empty by comparingfrontIndex
andrearIndex
.
- The
- Size Operation:
- The
size()
method returns the current size of the queue by calculating the difference betweenrearIndex
andfrontIndex
.
- The