Queue
In computer science, a queue is a linear data structure that follows the First In, First Out
(FIFO) principle. This means that the first element added to the queue is the first one to be removed.
How a Queue Works
Think of a queue as a line of people waiting to enter a theater. The person who arrives first gets to enter the theater first, while the person who arrives later has to wait at the end of the line. Similarly, in a queue, elements are enqueued at the back and dequeued from the front.
Queue Operations
A queue typically supports two main operations:
- Enqueue: Adds an element at the back of the queue.
- Dequeue: Removes the element from the front of the queue.
Additionally, a queue can provide the following operations:
- Front: Returns the value of the front element without removing it.
- Empty: Checks if the queue is empty.
Implementing a Queue in C++
In C++, you can use the std::queue
container class to implement a queue. The std::queue
class is a container adapter that uses a deque as its underlying container.
Here's an example of creating and using a queue in C++:
xxxxxxxxxx
int main() {
// Creating a queue
std::queue<int> myQueue;
// Enqueuing elements
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
// Checking if the queue is empty
bool empty = myQueue.empty();
// Getting the front element
int frontElement = myQueue.front();
// Dequeuing elements
myQueue.pop();
return 0;
}