The queue in the C++ Standard Template Library (STL) is a container adapter that operates in a First-In-First-Out (FIFO) manner.
Elements are added at the back (end) and removed from the front, making it suitable for scenarios where data needs to be processed in the order it arrives.
Key Features of queue
- FIFO Structure: Elements are processed in the order they were added.
- Efficient Operations: push, pop, front, and back operations are constant time.
- Restricted Access: Only the front and back elements can be accessed directly.
Basic Syntax
#include <queue> using namespace std; queue<Type> q;
Let’s explore the queue with examples demonstrating common operations.
1. Basic Operations: push, pop, front, and back
The push function adds an element to the back of the queue, pop removes an element from the front, front retrieves the first element, and back retrieves the last element.
#include <iostream> #include <queue> using namespace std; int main() { queue<int> q; // Adding elements q.push(10); q.push(20); q.push(30); // Access front and back elements cout << "Front element: " << q.front() << endl; cout << "Back element: " << q.back() << endl; // Remove elements and display them cout << "Elements in the queue: "; while (!q.empty()) { cout << q.front() << " "; q.pop(); } cout << endl; return 0; }
Output:
Front element: 10 Back element: 30 Elements in the queue: 10 20 30
2. Checking if the Queue is Empty
The empty function checks if the queue is empty, returning true if it is and false otherwise.
#include <iostream> #include <queue> using namespace std; int main() { queue<int> q; // Check if the queue is empty if (q.empty()) { cout << "The queue is empty." << endl; } // Add an element and check again q.push(5); if (!q.empty()) { cout << "The queue is not empty." << endl; } return 0; }
Output:
The queue is empty. The queue is not empty.
3. Getting the Size of the Queue
Use the size function to retrieve the number of elements in the queue.
#include <iostream> #include <queue> using namespace std; int main() { queue<int> q; // Insert elements q.push(10); q.push(20); q.push(30); // Display the size of the queue cout << "Size of the queue: " << q.size() << endl; return 0; }
Output:
Size of the queue: 3
4. Using queue with Custom Data Types
You can store custom objects in a queue as long as they have a valid copy constructor and assignment operator.
#include <iostream> #include <queue> #include <string> using namespace std; // Custom structure for storing person information struct Person { string name; int age; Person(string n, int a) : name(n), age(a) {} }; int main() { queue<Person> q; // Insert custom objects q.push(Person("Alice", 25)); q.push(Person("Bob", 30)); q.push(Person("Charlie", 35)); // Access and display elements cout << "People in the queue:" << endl; while (!q.empty()) { Person p = q.front(); cout << "Name: " << p.name << ", Age: " << p.age << endl; q.pop(); } return 0; }
Output:
People in the queue: Name: Alice, Age: 25 Name: Bob, Age: 30 Name: Charlie, Age: 35
5. Processing All Elements in the Queue
You can process each element in the queue by repeatedly using front to access it, and pop to remove it.
#include <iostream> #include <queue> using namespace std; int main() { queue<int> q; // Insert elements q.push(5); q.push(10); q.push(15); cout << "Processing elements in the queue: "; while (!q.empty()) { // Process the front element int val = q.front(); cout << val << " "; q.pop(); // Remove the element } cout << endl; return 0; }
Output:
Processing elements in the queue: 5 10 15
6. Using queue with Strings
You can also use queue to manage strings, making it easy to process string data in FIFO order.
#include <iostream> #include <queue> #include <string> using namespace std; int main() { queue<string> q; // Insert strings q.push("apple"); q.push("banana"); q.push("cherry"); // Display and remove strings in FIFO order cout << "Strings in the queue: "; while (!q.empty()) { cout << q.front() << " "; q.pop(); } cout << endl; return 0; }
Output:
Strings in the queue: apple banana cherry
7. Using queue to Simulate a Simple Task Scheduler
You can use queue to simulate a task scheduler, where tasks are processed in the order they are added.
#include <iostream> #include <queue> #include <string> using namespace std; // Custom structure for tasks struct Task { string description; int priority; Task(string desc, int prio) : description(desc), priority(prio) {} }; int main() { queue<Task> taskQueue; // Add tasks to the queue taskQueue.push(Task("Process data", 1)); taskQueue.push(Task("Save file", 2)); taskQueue.push(Task("Send email", 3)); // Process tasks in FIFO order cout << "Processing tasks:" << endl; while (!taskQueue.empty()) { Task t = taskQueue.front(); cout << "Task: " << t.description << ", Priority: " << t.priority << endl; taskQueue.pop(); } return 0; }
Output:
Processing tasks: Task: Process data, Priority: 1 Task: Save file, Priority: 2 Task: Send email, Priority: 3
8. Clearing All Elements from a Queue
To clear all elements in a queue, use a loop to remove each element with pop.
#include <iostream> #include <queue> using namespace std; int main() { queue<int> q; // Insert elements q.push(10); q.push(20); q.push(30); // Clear the queue while (!q.empty()) { q.pop(); } // Verify that the queue is empty cout << "Is the queue empty? " << (q.empty() ? "Yes" : "No") << endl; return 0; }
Output:
Is the queue empty? Yes
9. Using queue with Arrays
You can initialize a queue with elements from an array by looping through the array.
#include <iostream> #include <queue> using namespace std; int main() { int arr[] = {1, 2, 3, 4, 5}; queue<int> q; // Insert array elements into the queue for (int num : arr) { q.push(num); } // Display elements cout << "Elements in the queue: "; while (!q.empty()) { cout << q.front() << " "; q.pop(); } cout << endl; return 0; }
Output:
Elements in the queue: 1 2 3 4 5
10. Using queue with Vectors
You can also initialize a queue with elements from a vector.
#include <iostream> #include <queue> #include <vector> using namespace std; int main() { vector<int> vec = {1, 2, 3, 4, 5}; queue<int> q; // Insert vector elements into the queue for (int num : vec) { q.push(num); } // Display elements cout << "Elements in the queue: "; while (!q.empty()) { cout << q.front() << " "; q.pop(); } cout << endl; return 0; }
Output:
Elements in the queue: 1 2 3 4 5
Summary Table of queue Operations
Operation | Code Example | Description |
---|---|---|
Initialize | queue<int> q; | Initializes an empty queue |
Add Element | q.push(10); | Adds an element to the back of the queue |
Remove Element | q.pop(); | Removes the front element |
Access Front | q.front(); | Accesses the front element |
Access Back | q.back(); | Accesses the back element |
Check if Empty | q.empty(); | Returns true if the queue is empty |
Get Size | q.size(); | Returns the number of elements in the queue |
Custom Data Types | queue<CustomType> q; | Stores custom objects |
Process All Elements | Use while(!q.empty()) { q.pop(); } | Clears all elements manually |
Initialize from Array | for (int x : arr) q.push(x); | Adds elements from an array |
Initialize from Vector | for (int x : vec) q.push(x); | Adds elements from a vector |
Complete Example: Using Multiple queue Operations
This example demonstrates initializing a queue, adding and removing elements, checking the front and back elements, and clearing the queue.
#include <iostream> #include <queue> using namespace std; int main() { queue<int> q; // Adding elements q.push(5); q.push(10); q.push(15); // Display front and back elements cout << "Front element: " << q.front() << endl; cout << "Back element: " << q.back() << endl; // Display all elements in the queue cout << "Elements in the queue: "; while (!q.empty()) { cout << q.front() << " "; q.pop(); } cout << endl; // Check if queue is empty after clearing cout << "Is the queue empty? " << (q.empty() ? "Yes" : "No") << endl; return 0; }
Sample Output:
Front element: 5 Back element: 15 Elements in the queue: 5 10 15 Is the queue empty? Yes
Key Takeaways
- queue in C++ provides a simple way to manage a collection of elements in a FIFO manner.
- Key operations include push, pop, front, back, empty, and size.
- Ideal for tasks like managing buffers, task scheduling, and processing elements sequentially where order matters.