0
0
CppHow-ToBeginner · 3 min read

How to Implement Queue in C++: Syntax and Example

In C++, you can implement a queue using the std::queue container from the Standard Template Library (STL). It provides simple methods like push() to add elements, pop() to remove elements, and front() to access the first element in the queue.
📐

Syntax

The std::queue is a container adapter that gives FIFO (First In First Out) behavior. You include it with #include <queue>. The main methods are:

  • push(value): Adds value to the back of the queue.
  • pop(): Removes the front element.
  • front(): Accesses the front element.
  • empty(): Checks if the queue is empty.
  • size(): Returns the number of elements.
cpp
#include <queue>

std::queue<Type> queue_name;

queue_name.push(value);   // Add element
queue_name.pop();         // Remove front element
Type front = queue_name.front(); // Access front element
bool isEmpty = queue_name.empty();
size_t count = queue_name.size();
💻

Example

This example shows how to create a queue of integers, add elements, access the front, and remove elements until the queue is empty.

cpp
#include <iostream>
#include <queue>

int main() {
    std::queue<int> q;

    // Add elements
    q.push(10);
    q.push(20);
    q.push(30);

    // Process queue
    while (!q.empty()) {
        std::cout << "Front element: " << q.front() << "\n";
        q.pop();
    }

    return 0;
}
Output
Front element: 10 Front element: 20 Front element: 30
⚠️

Common Pitfalls

Common mistakes when using std::queue include:

  • Trying to access the front element when the queue is empty causes undefined behavior.
  • Using pop() does not return the removed element; you must call front() before pop() to get the value.
  • Confusing std::queue with std::priority_queue, which orders elements differently.
cpp
#include <queue>
#include <iostream>

int main() {
    std::queue<int> q;

    // Wrong: popping without checking empty
    // q.pop(); // Unsafe if queue is empty

    // Correct way:
    if (!q.empty()) {
        int val = q.front();
        q.pop();
        std::cout << val << " removed\n";
    }

    return 0;
}
📊

Quick Reference

Here is a quick summary of std::queue methods:

MethodDescription
push(value)Add element to the back
pop()Remove front element
front()Access front element
empty()Check if queue is empty
size()Get number of elements

Key Takeaways

Use std::queue from the STL for easy FIFO queue implementation in C++.
Always check empty() before accessing front() or calling pop() to avoid errors.
pop() removes the front element but does not return it; use front() to get the value first.
std::queue provides simple methods to add, remove, and access elements in FIFO order.
Remember to include <queue> and use the std namespace or prefix.