Topic 66 of 83
Container Adapters
Overview
Adapters restrict the interface of existing containers to provide specific behavior. `stack` is LIFO. `queue` is FIFO. `priority_queue` is a Heap (highest value pops first).
Syntax
cpp
#include <stack>
#include <queue>
// Stack (Last In, First Out)
std::stack<int> st;
st.push(1); st.push(2);
st.pop(); // Removes 2
// Queue (First In, First Out)
std::queue<int> q;
q.push(1); q.push(2);
q.front(); // 1
q.pop(); // Removes 1
// Priority Queue (Max Heap by default)
std::priority_queue<int> pq;
pq.push(10); pq.push(50); pq.push(20);
pq.top(); // 50Common Pitfalls
- Trying to iterate through a stack or queue. Adapters do NOT support iterators. You must `pop()` elements to view the ones underneath.
Interview Tips
- To make a Min-Heap (smallest value pops first), use this verbose syntax: `std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;` (Asked frequently in interviews!)
Real-World Example
Using a Priority Queue for Task Scheduling.
example
cpp
#include <iostream>
#include <queue>
using namespace std;
int main() {
// Automatically sorts tasks so highest priority (number) is always on top
priority_queue<int> tasks;
tasks.push(3); // Medium priority
tasks.push(9); // Critical priority
tasks.push(1); // Low priority
cout << "Executing task with priority: " << tasks.top() << endl; // 9
tasks.pop(); // Remove 9
return 0;
}