STL Containers¶
The Standard Template Library (STL) provides robust, efficient containers. Knowing which one to use is key to writing high-performance C++.
Sequence Containers¶
std::vector (The Default Choice)¶
A dynamic array that grows automatically. - Access: O(1) - Insert at end: Amortized O(1) - Insert in middle: O(n)
std::array (Fixed Size)¶
A thin wrapper around C-style arrays. Allocated on the stack (usually). - Size: Fixed at compile-time. - Performance: Zero overhead.
std::string¶
A specialized container for text. - Small String Optimization (SSO): Short strings are stored directly in the object, avoiding heap allocation.
Associative Containers¶
std::map vs std::unordered_map¶
| Feature | std::map |
std::unordered_map |
|---|---|---|
| Implementation | Balanced Binary Tree (Red-Black) | Hash Table |
| Order | Sorted by Key | Undefined |
| Search Time | O(log n) | O(1) Average |
std::set and std::unordered_set¶
Similar to maps, but store unique keys only.
Pairs and Tuples¶
Utilities to bundle multiple values.
std::pair¶
Holds two values.
std::tuple¶
Holds N values.
Iterators¶
Iterators are objects that point to elements in a container. They generalize pointers.
begin(): Points to the first element.end(): Points past the last element.
Modern Views (Non-owning)¶
These are lightweight objects that refer to data owned by other containers. They prevent unnecessary copies.
std::string_view (C++17)¶
A read-only view of a string (or part of it).
std::span (C++20)¶
A view of a contiguous sequence of objects (like an array or vector).
Container Adapters¶
std::stack: LIFO (Last In, First Out).std::queue: FIFO (First In, First Out).std::priority_queue: Elements are popped in priority order (default: largest first).