Lesson 24 of 45 · C++
Lesson 30: Deque Container
Duration: 9 min
Lesson 24 of 45 · C++
Duration: 9 min
std::deque (double‑ended queue) provides fast insertions and deletions at both the front and back while still supporting random access iterators.\n\n---\n\n## When to use\n- Implementing BFS queues, sliding windows, or buffers where both ends are manipulated frequently.\n- Need for contiguous blocks of memory for cache friendliness is less important than for vector.\n\n---\n\n## Example: Simulating a simple queue with a deque\ncpp\nstd::deque<int> dq;\n// Push at the back\ndq.push_back(1);\ndq.push_back(2);\n// Push at the front\ndq.push_front(0);\n// Pop from the front (FIFO)\nint front = dq.front();\ndq.pop_front();\nstd::cout << \"Popped \" << front << \", remaining:\";\nfor (int v : dq) std::cout << ' ' << v;\nstd::cout << '\\n';\n\n\nThe deque grows in chunks, so it does not need to relocate all existing elements when expanding, unlike vector.\n\n> Tip: If you only need front‑or‑back operations, std::vector (with push_back) or std::list may be more appropriate depending on performance characteristics.\n\n---\n\n<Alert type="warning">std::deque does not guarantee a single contiguous memory block; pointer stability is only guaranteed for elements inserted at the front or back, not for random access via operator[] after reallocation.