Loading lessons...
Queues (std::queue)
Queues (std::queue)
A queue works like a ticket counter line: the first person in line is served first. That is FIFO - First In, First Out.
Create a queue
#include <queue>
std::queue<int> line;
Add at the back, look at the ends
line.push(10); // line is now {10}
line.push(20); // line is now {10, 20}
std::cout << line.front() << "\n"; // 10, the oldest
std::cout << line.back() << "\n"; // 20, the newest
push(x)adds to the back.front()reads the oldest element (the one that goes next).back()reads the newest element just arrived.
pop removes from the front
line.pop(); // removes 10, the front
Like a stack, pop() returns nothing - read front() first if you need the value.
Drain the queue in order
while (!line.empty()) {
std::cout << line.front() << "\n";
line.pop();
}
This prints the elements in the order they were added, oldest first.
TL;DR
- A queue follows FIFO: push to the back, leave the front.
push(x)/front()/back()/pop()are the queue basics.pop()removes the oldest element and returns nothing.empty()andsize()report the state of the line.- Read
front()beforepop()in a loop to serve the queue.