C++ Day 39
STL Containers (Deep Understanding & Real Usage)
Till now, you already know arrays, vectors, loops, and STL algorithms.
Today, we go one step deeper and understand STL containers, which are the backbone of modern C++ programming.
In real projects and competitive coding, choice of container matters a lot.
1. What are STL Containers?
STL containers are data structures provided by C++ to store data efficiently.
They handle:
-
memory management
-
resizing
-
element access
-
performance optimization
You focus on logic, not memory handling.
2. Categories of STL Containers
STL containers are mainly divided into:
-
Sequence Containers
-
Associative Containers
-
Unordered Containers
-
Container Adapters
3. Sequence Containers
These store data in sequence.
3.1 Vector
Most used container in C++.
Key Features:
-
Dynamic size
-
Contiguous memory
-
Fast random access
-
Slower insertion in middle
Example:
When to Use Vector:
-
When index access is needed
-
When size changes frequently
-
Competitive programming
3.2 Deque (Double Ended Queue)
Features:
-
Fast insertion at front and back
-
Random access supported
-
Slightly slower than vector
3.3 List (Doubly Linked List)
Features:
-
Non-contiguous memory
-
Fast insertion and deletion anywhere
-
No random access
Use when frequent insert/delete in middle is required.
4. Associative Containers (Ordered)
These store data in sorted order.
4.1 Set
Properties:
-
Stores unique elements
-
Sorted automatically
-
Implemented using Red-Black Tree
4.2 Multiset
Allows duplicate values.
4.3 Map
Stores key-value pairs.
Example:
-
Keys are unique
-
Automatically sorted by key
5. Unordered Containers
These use hashing.
5.1 Unordered Set
-
Unique elements
-
No order
-
Faster than set in most cases
5.2 Unordered Map
Used heavily in frequency counting.
Average complexity is O(1).
6. Container Adapters
These provide restricted access.
6.1 Stack
LIFO (Last In First Out)
6.2 Queue
FIFO (First In First Out)
6.3 Priority Queue
-
Max heap by default
For min heap:
7. Choosing the Right Container
| Requirement | Container |
|---|---|
| Fast access by index | vector |
| Insert/delete in middle | list |
| Unique sorted data | set |
| Key-value pair | map |
| Fast lookup | unordered_map |
| Max/Min element | priority_queue |
8. Real-World Example
Counting frequency of numbers:
Used in:
-
interview problems
-
data analysis
-
competitive coding
9. Common Mistakes
-
Using map instead of unordered_map unnecessarily
-
Using vector when frequent middle insertion is needed
-
Forgetting that set/map are sorted
-
Expecting index access in list or set
10. Summary (Day 39)
Today you learned:
-
Types of STL containers
-
Differences between them
-
When to use which container
-
Real-world usage patterns
-
Performance considerations
Comments
Post a Comment