C++ Data Structures and STL
🧩 C++ Data Structures and STL (Standard Template Library)
Data Structures organize data efficiently, and the STL provides ready-made, high-performance implementations using templates.
STL saves time, reduces bugs, and is the standard way to work with collections in modern C++.
🔹 1. What Is STL?
The STL is a collection of generic classes and functions. It has four main components:
Containers – store data
Algorithms – process data
Iterators – traverse data
Functors (function objects) – customizable behavior
🔹 2. STL Containers
🔸 Sequence Containers (ordered, indexed)
vector– dynamic array (most used)deque– double-ended queuelist– doubly linked listarray– fixed-size array (C++11)forward_list– singly linked list
🔸 Associative Containers (sorted)
set– unique keysmultiset– duplicate keysmap– key–value, unique keysmultimap– key–value, duplicate keys
🔸 Unordered Containers (hash-based, fast)
unordered_setunordered_mapunordered_multisetunordered_multimap
🔸 Container Adapters
stack– LIFOqueue– FIFOpriority_queue– heap (max by default)
🔹 3. STL Algorithms (<algorithm>)
Common algorithms (work with iterators):
With lambda:
🔹 4. Iterators
Iterators act like pointers to container elements.
Types:
Input, Output
Forward, Bidirectional
Random Access (e.g.,
vector)
🔹 5. Functors (Function Objects)
Objects that behave like functions.
Often replaced by lambdas today.
🔹 6. Choosing the Right Data Structure
| Use Case | Best Choice |
|---|---|
| Fast indexing | vector, array |
| Frequent insert/delete (middle) | list |
| Sorted unique data | set |
| Key–value lookup | map |
| Fast hash lookup | unordered_map |
| LIFO | stack |
| FIFO | queue |
🔹 7. Complexity (Big-O Highlights)
vectoraccess: O(1)mapinsert/search: O(log n)unordered_mapaverage search: O(1)setinsert/search: O(log n)sort: O(n log n)
🔹 8. Example: Word Frequency Counter
🔹 9. STL vs Custom Data Structures
| STL | Custom |
|---|---|
| Tested & optimized | Risk of bugs |
| Faster development | More control |
| Generic | Specific |
| Standard | Custom behavior |
🔹 10. Best Practices
Prefer STL containers over raw arrays
Use
autowith iteratorsPass containers by
const&Use
unordered_*for speed,map/setfor orderCombine algorithms + lambdas for clean code
📌 Summary
STL provides ready-made data structures & algorithms
Containers store data; algorithms process it
Iterators connect containers and algorithms
Use the right container for the problem
Essential for interviews and real-world C++ projects
