C++ queues
In C++, a queue is a container adaptor in the C++ Standard Library that follows the First In First Out (FIFO) principle. It is defined in the <queue> header file. A queue is a data structure where elements are added at the back (enqueue operation) and removed from the front (dequeue operation). This makes queues useful for tasks that require ordered processing, like task scheduling, simulation, or message handling.
Queues are typically implemented using underlying containers like std::deque
or std::list
. However, the std::queue
provides a simplified interface for working with them.
std::queue
std::queue
uses another container (like std::deque
or std::list
) to store the elements.To declare a queue:
std::queue<T> queue_name;
Where:
T
: Type of the elements (e.g., int
, std::string
).You can also initialize a queue with a specific container:
std::queue<T, Container> queue_name;
Where Container
can be std::deque
(default) or std::list
.
#include <iostream>
#include <queue>
int main() {
// Declare a queue of integers
std::queue<int> q;
// Enqueue elements
q.push(10);
q.push(20);
q.push(30);
// Displaying the front element
std::cout << "Front of the queue: " << q.front() << std::endl; // Output: 10
return 0;
}
Explanation:
push()
is used to add elements to the queue.front()
returns the element at the front of the queue.std::queue
push()
Adds an element to the back of the queue.
q.push(40); // Adds 40 to the back of the queue
pop()
Removes the element at the front of the queue.
q.pop(); // Removes the front element from the queue
front()
Returns a reference to the element at the front of the queue.
std::cout << "Front element: " << q.front() << std::endl;
back()
Returns a reference to the element at the back of the queue.
std::cout << "Back element: " << q.back() << std::endl;
size()
Returns the number of elements in the queue.
std::cout << "Size of the queue: " << q.size() << std::endl;
empty()
Checks if the queue is empty.
if (q.empty()) {
std::cout << "The queue is empty!" << std::endl;
} else {
std::cout << "The queue is not empty!" << std::endl;
}
Unlike other containers, such as vectors or lists, queues do not allow direct access to their elements via iterators. To iterate through a queue, you need to pop elements one by one and process them.
#include <iostream>
#include <queue>
int main() {
std::queue<int> q;
q.push(10);
q.push(20);
q.push(30);
// Iterating through the queue by popping elements
while (!q.empty()) {
std::cout << q.front() << " "; // Print the front element
q.pop(); // Remove the front element
}
return 0;
}
Explanation:
pop()
to remove the front element until the queue is empty.front()
function provides access to the first element.std::queue
Over Other Containersstd::queue
provides a minimal interface, focusing on the essential operations required for queue management without exposing unnecessary details.std::queue
Use std::queue
when: