Stacks and Queues
Queue Enqueue/Dequeue
Enqueue values at the back and dequeue them from the front in first-in, first-out order.
Algorithm
Basic Implementation
basic.cpp
#include <deque>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
string render(const vector<int>& values) {
ostringstream out;
for (size_t i = 0; i < values.size(); ++i) {
if (i > 0) out << " -> ";
out << values[i];
}
return out.str();
}
int main() {
deque<int> queue;
for (int value : {10, 20, 30}) queue.push_back(value);
vector<int> removed;
while (!queue.empty()) {
removed.push_back(queue.front());
queue.pop_front();
}
cout << render(removed) << endl;
}
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
- In C++, the checked source uses
std::deque<int> queuedirectly rather than thestd::queueadapter, so the front/back operations are visible in source. - Enqueue is
queue.push_back(value)over the initializer list{10, 20, 30}; dequeue readsqueue.front()intoremoved.push_back(...)beforequeue.pop_front()mutates the deque. - The loop guard is
while (!queue.empty()), sofront()andpop_front()are only called on a non-empty deque in the checked path. - Dequeued values are copied into a
std::vector<int> removed; the deque values themselves are integers, so there is no object ownership transfer. - The trace records queue
[], then[10, 20, 30], then removed[10]with queue[20, 30], ending with removed[10, 20, 30]and queue[]. render(const std::vector<int>&)usesstd::ostringstreamand asize_tloop to produce10 -> 20 -> 30, which is printed withstd::cout.- Visible allocation is the deque storage, the removed vector, and the output string buffer; mutation happens in the deque and removed vector.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.