The queue container in C++ provides a simple and efficient way to implement a queue data structure. It follows the First-In-First-Out (FIFO) principle, where elements are inserted at the back and removed from the front. The queue container is part of the C++ Standard Template Library (STL) and is included in the <queu> header.
Step 1: Include the necessary header file
#include<queue>
Step 2: Declare a queue object
std::queue<T> myQueue;
Replace T with the type of elements you want to store in the queue.
Step 3: Insert elements into the queue
myQueue.push(element);
This adds the element to the back of the queue.
Step 4: Access the front element
T frontElement = myQueue.front();
This retrieves the front element of the queue without removing it.
Step 5: Remove the front element
myQueue.pop();
This removes the front element from the queue.
Step 6: Check if the queue is empty
bool isEmpty = myQueue.empty();
This returns true if the queue is empty; otherwise, it returns false.
Step 7: Get the size of the queue
size_t queueSize = myQueue.size();
This returns the number of elements currently stored in the queue.
Here's an example that demonstrates the usage of queue:
#include<iostream> #include<queue> int main() { std::queue<int> myQueue; // Insert elements into the queue myQueue.push(10); myQueue.push(20); myQueue.push(30); // Access the front element int frontElement = myQueue.front(); std::cout << "Front element: " << frontElement << std::endl; // Remove the front element myQueue.pop(); // Check if the queue is empty bool isEmpty = myQueue.empty(); std::cout << "Is queue empty? " << (isEmpty ? "Yes" : "No") << std::endl; // Get the size of the queue size_t queueSize = myQueue.size(); std::cout << "Queue size: " << queueSize << std::endl; return 0; }
Output:
Front element: 10 Is queue empty? No Queue size: 2