Container Adapters
Overview
Sometimes you don't want a new data structure; you just want to restrict how an existing one is used to enforce strict architectural rules.
Container Adapters (std::stack, std::queue, std::priority_queue) do not build their own memory. Instead, they 'wrap' around an existing Sequence Container (like a Deque or Vector) and disable almost all of its functions. A Stack (LIFO: Last-In, First-Out) disables everything except pushing and popping from the top. A Queue (FIFO: First-In, First-Out) strictly enforces lines (like a server processing requests).
Syntax
#include <iostream>
#include <stack>
#include <queue>
int main() {
// --- 1. STACK (LIFO: Like a stack of plates) ---
std::stack<int> history;
history.push(10);
history.push(20);
std::cout << "Stack Top: " << history.top() << "\n"; // 20
history.pop(); // Removes 20!
// --- 2. QUEUE (FIFO: Like a line at a store) ---
std::queue<int> line;
line.push(10);
line.push(20);
std::cout << "Queue Front: " << line.front() << "\n"; // 10
line.pop(); // Removes 10!
return 0;
}Common Pitfalls
- Assuming
.pop()returns the value. In Python or Java, callingpop()removes the item AND returns it to you. In C++,.pop()strictly returnsvoid(nothing). To retrieve and remove an item safely in C++, you MUST call.top()to read it first, and then call.pop()to delete it.
Interview Questions
priority_queue in C++, and what underlying data structure powers it?A priority queue does not operate on First-In-First-Out. Instead, every time you push an element, it instantly sorts itself so the 'highest priority' (largest) element is always at the absolute front. Under the hood, it is powered by a 'Max Heap' binary tree architecture mapped over a std::vector, guaranteeing O(log N) insertions.
Real-World Example
Using a Priority Queue to build a Hospital Triage system, where critical patients jump to the front of the line automatically.
#include <iostream>
#include <queue>
int main() {
// By default, C++ priority_queue puts the LARGEST integer at the front
std::priority_queue<int> triageLine;
triageLine.push(2); // Sprained ankle (Severity 2)
triageLine.push(9); // Heart attack (Severity 9)
triageLine.push(5); // Broken arm (Severity 5)
// The queue automatically rearranged them!
std::cout << "Next patient severity: " << triageLine.top() << "\n"; // 9
return 0;
}Check Your Knowledge
Test your understanding of Container Adapters with these quick questions.