C++ Iterators
π C++ Iterators
Iterators in C++ act like pointers that allow you to traverse and access elements of STL containers (vector, list, map, set, etc.).
They form the bridge between containers and algorithms.
πΉ 1. Why Iterators?
Traverse containers in a uniform way
Work with STL algorithms (
sort,find,count, etc.)Abstract container internals
Type-safe and flexible
πΉ 2. Basic Iterator Syntax
Example:
Modern way:
πΉ 3. Common Iterator Functions
| Function | Description |
|---|---|
begin() | Points to first element |
end() | Points after last element |
rbegin() | Reverse begin |
rend() | Reverse end |
πΉ 4. Iterating a Container
Vector Example
Reverse Iteration
πΉ 5. Iterators with map
πΉ 6. Types of Iterators
1οΈβ£ Input Iterator
Read only
One-direction
2οΈβ£ Output Iterator
Write only
3οΈβ£ Forward Iterator
Read & write
One-direction
4οΈβ£ Bidirectional Iterator
Forward + backward
(
list,set,map)
5οΈβ£ Random Access Iterator
Jump to any position
(
vector,deque,array)
πΉ 7. const_iterator
Prevents modification of elements.
πΉ 8. Iterator Arithmetic
β Only for random-access iterators:
β Invalid for list or set
πΉ 9. Iterator with Algorithms
πΉ 10. Invalidated Iterators (Important!)
Some operations invalidate iterators.
β Safer with list
πΉ 11. Range-based Loop vs Iterators
β Simpler
β Less control than iterators
β Common Mistakes
π Summary
Iterators act like pointers
Used to traverse STL containers
Required for STL algorithms
Different containers support different iterator types
Be careful with iterator invalidation
