Iterators in C++ are objects that are used to access and traverse elements of containers like vectors, lists, and maps in the Standard Template Library (STL).
What is an Iterator?
An iterator works like a pointer. It points to elements inside a container and allows you to move through them one by one.
Why Use Iterators?
Iterators are useful because they:
- Provide a common way to access STL containers
- Work with different data structures
- Replace indexing in containers like lists and maps
- Make code more flexible and reusable
Basic Syntax
container_type::iterator it;
Iterator with Vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {10, 20, 30};
vector<int>::iterator it;
for (it = v.begin(); it != v.end(); it++) {
cout << *it << endl;
}
return 0;
}
Output
10
20
30
How Iterators Work
begin()points to the first elementend()points just after the last element*itaccesses the valueit++moves to next element
Simplified Iterator Loop
Modern C++ uses auto keyword.
for (auto it = v.begin(); it != v.end(); it++) {
cout << *it << endl;
}
Iterator with List
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> l = {1, 2, 3};
for (auto it = l.begin(); it != l.end(); it++) {
cout << *it << endl;
}
return 0;
}
Iterator with Map
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> m;
m["Ali"] = 80;
m["Ahmed"] = 90;
for (auto it = m.begin(); it != m.end(); it++) {
cout << it->first << " : " << it->second << endl;
}
return 0;
}
Output
Ali : 80
Ahmed : 90
Types of Iterators
- Input Iterator
- Output Iterator
- Forward Iterator
- Bidirectional Iterator
- Random Access Iterator
Important Iterator Operations
| Operation | Meaning |
|---|---|
*it | Access value |
it++ | Move forward |
it-- | Move backward (some containers) |
it-> | Access object members |
Why Iterators are Important
Iterators are important because they:
- Work with all STL containers
- Replace indexing in complex structures
- Make code generic and reusable
- Help in efficient traversal
Difference Between Iterator and Pointer
| Iterator | Pointer |
|---|---|
| Works with STL containers | Works with memory addresses |
| Safer and more flexible | Low-level access |
| Supports different containers | Works mainly with arrays |
Real-Life Example
Think of iterators like reading pages of a book:
- Start from first page
- Move page by page
- Stop at the end
This is how iterators move through data.
Applications of Iterators
Iterators are used in:
- Data traversal in STL containers
- Algorithms like sorting and searching
- Complex data structure handling
- Generic programming
Conclusion
Iterators in C++ are powerful tools used to traverse and access elements in STL containers. They provide a standard and flexible way to work with different data structures, making code more efficient and reusable.