How to Use Queue in C++: Syntax, Example, and Tips
In C++, you use the
std::queue container from the <queue> header to create a queue. It works like a line where elements are added at the back using push() and removed from the front using pop().Syntax
The std::queue is a container adapter that provides FIFO (First In First Out) behavior. You include it with #include <queue>. The main operations are:
push(value): Adds an element to the back.pop(): Removes the front element.front(): Accesses the front element.back(): Accesses the last element.empty(): Checks if the queue is empty.size(): Returns the number of elements.
cpp
#include <queue> std::queue<Type> q; q.push(value); // Add element to back q.pop(); // Remove front element Type front = q.front(); // Access front element Type back = q.back(); // Access last element bool isEmpty = q.empty(); size_t count = q.size();
Example
This example shows how to create a queue of integers, add elements, access the front and back, remove elements, and check if it is empty.
cpp
#include <iostream> #include <queue> int main() { std::queue<int> q; q.push(10); q.push(20); q.push(30); std::cout << "Front element: " << q.front() << "\n"; std::cout << "Back element: " << q.back() << "\n"; std::cout << "Queue size: " << q.size() << "\n"; q.pop(); // removes 10 std::cout << "After pop, front element: " << q.front() << "\n"; std::cout << "Is queue empty? " << (q.empty() ? "Yes" : "No") << "\n"; return 0; }
Output
Front element: 10
Back element: 30
Queue size: 3
After pop, front element: 20
Is queue empty? No
Common Pitfalls
Common mistakes when using std::queue include:
- Trying to access
front()orback()when the queue is empty, which causes undefined behavior. - Forgetting to
pop()elements, leading to memory growth. - Using
pop()expecting it to return the removed element; it does not return anything.
Always check empty() before accessing or popping.
cpp
#include <queue> #include <iostream> int main() { std::queue<int> q; // Wrong: Access front when empty // std::cout << q.front(); // Undefined behavior! // Right way: if (!q.empty()) { std::cout << q.front(); } else { std::cout << "Queue is empty."; } return 0; }
Output
Queue is empty.
Quick Reference
Remember these key points when using std::queue:
- Use
push()to add elements at the back. - Use
pop()to remove elements from the front. - Use
front()andback()to access elements. - Always check
empty()before accessing or popping. pop()does not return the removed element.
Key Takeaways
Use
std::queue from <queue> for FIFO data structure in C++.Add elements with
push() and remove with pop().Always check
empty() before accessing front() or back().pop() does not return the removed element; call front() first if needed.Queue size can be checked with
size().