C++
Module 22: STL – Standard Template LibraryIntermediate50 min read

STL Sequence Containers & Adaptors (vector, array, deque, stack, queue, priority_queue)

Master STL architecture, std::vector, std::array, std::deque, std::list, and adaptors (stack, queue, priority_queue) with time complexities.

Key Takeaways & Core Concepts
  • | Contiguous dynamic array | O(1) | O(1) amortized | O(n) |
  • | Fixed stack array | O(1) | N/A | N/A |
  • | Chunked blocks | O(1) | O(1) | O(1) |
  • | Doubly linked list | O(n) | O(1) | O(1) |

1. STL Architecture: Containers, Iterators & Algorithms

STL decouples data structures from algorithms via iterators, allowing std::sort, std::find, and std::reverse to work uniformly across containers.

1. vector::reserve & priority_queue Min-Heap
1#include <iostream>
2#include <vector>
3#include <queue>
4
5int main() {
6 std::vector<int> v;
7 v.reserve(4);
8 v.push_back(15); v.push_back(5); v.push_back(25);
9
10 std::priority_queue<int, std::vector<int>, std::greater<int>> pq(v.begin(), v.end());
11 while (!pq.empty()) {
12 std::cout << pq.top() << " ";
13 pq.pop();
14 }
15 return 0;
16}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
16 lines
Note: Reserves capacity upfront and builds a min-heap in O(n) from iterators.

2. Sequence Containers & Adaptors Comparison

ContainerInternal StructureRandom AccessInsert/Erase BackInsert/Erase Front
`std::vector`Contiguous dynamic arrayO(1)O(1) amortizedO(n)
`std::array`Fixed stack arrayO(1)N/AN/A
`std::deque`Chunked blocksO(1)O(1)O(1)
`std::list`Doubly linked listO(n)O(1)O(1)
`std::priority_queue`Binary HeapTop only O(1)O(log n) pushO(log n) pop

3. Iterator Invalidation Warning

Calling push_back() on a std::vector when size() == capacity() reallocates the buffer, invalidating all existing pointers, references, and iterators! Use reserve(n) when the size is known.

Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)