The Standard Template Library (STL)
The STL is C++‘s superpower. It provides efficient, tested, and reusable components. Rule #1 of C++: If it’s in the STL, don’t write it yourself. Why write a buggy linked list whenstd::list exists and is optimized by experts?
1. Containers
Containers are data structures that store collections of objects. They manage memory automatically.Sequential Containers (Ordered)
std::vector (Dynamic Array)
- What is it?: An array that can grow.
- Use default: 99% of the time, use vector. It’s cache-friendly and fast.
- Operations: Fast access (
[]), fast push back. Slow insert in the middle.
std::array (Fixed-Size Array)
- What is it?: A safer version of C-style arrays (
int arr[5]). - Use when: Size is known at compile time and won’t change.
- Zero overhead: No dynamic allocation.
Associative Containers (Key-Value / Sorted)
std::map (Ordered Map)
- What is it?: A tree-based dictionary.
- Order: Keys are always sorted (alphabetically or numerically).
- Complexity: O(log n).
Unordered Containers (Hash Tables)
std::unordered_map
- What is it?: A hash table.
- Order: Random.
- Complexity: O(1) average (Very fast).
- Use when: You need fast lookups and don’t care about order.
2. Iterators
Iterators are the glue between Containers and Algorithms. Think of them as “smart pointers” that know how to navigate a specific container.begin(): Points to the first element.end(): Points to one past the last element.
Range-Based For Loop
This syntactic sugar uses iterators behind the scenes but is much cleaner.3. Algorithms
The<algorithm> header contains 100+ functions for sorting, searching, and manipulating ranges. They are often faster and less buggy than writing your own loops.
Sorting & Searching
Transformations
Finding
4. Lambdas (Anonymous Functions)
Lambdas allow you to write small, throwaway functions inline. They are perfect for passing to algorithms likesort or find_if.
Syntax: [capture](parameters) -> return_type { body }
Capture Clauses
[]: No capture. Function is isolated.[=]: Capture all local variables by value (copy).[&]: Capture all local variables by reference (can modify original).
Summary
- Containers: Use
std::vectorby default. Usestd::mapfor sorted keys,std::unordered_mapfor speed. - Iterators: Abstract the navigation of data.
- Algorithms: Prefer
std::sort,std::find, etc., over writing raw loops. - Lambdas: Write concise, local functions for algorithms.