Queue Basics
Basic Queue Operations in C++
BeginnerTopic: STL Containers Programs
C++ Queue Basics Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <queue>
using namespace std;
int main() {
// Create queue
queue<int> q;
// Enqueue elements
q.push(10);
q.push(20);
q.push(30);
q.push(40);
q.push(50);
cout << "Queue size: " << q.size() << endl;
cout << "Front element: " << q.front() << endl;
cout << "Back element: " << q.back() << endl;
// Display queue (by dequeuing)
cout << "\nQueue elements (FIFO - First In First Out):" << endl;
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
cout << endl;
// Queue for BFS-like processing
queue<string> taskQueue;
taskQueue.push("Task 1");
taskQueue.push("Task 2");
taskQueue.push("Task 3");
cout << "\nProcessing tasks:" << endl;
while (!taskQueue.empty()) {
cout << "Processing: " << taskQueue.front() << endl;
taskQueue.pop();
}
return 0;
}Output
Queue size: 5 Front element: 10 Back element: 50 Queue elements (FIFO - First In First Out): 10 20 30 40 50 Processing tasks: Processing: Task 1 Processing: Task 2 Processing: Task 3
Understanding Queue Basics
Queue is a FIFO (First In First Out) container. Operations: push(), pop(), front(), back(), empty(), size(). Elements are added at the back and removed from the front. Common uses: 1) BFS (Breadth-First Search), 2) Task scheduling, 3) Print queue management, 4) Message buffering. All operations are O(1) time complexity.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.