Iterators and Iterator Types in C++
Iterators in C++ are objects that act as pointers to elements within a container. They provide a way to traverse and access elements in data structures like vector, list, set, and more.
What Are Iterators?
An iterator is used to point to elements in a container and perform traversal operations. It abstracts away the details of how data is stored and allows access to elements sequentially.
Types of Iterators
There are five types of iterators in C++:
- Input Iterator: Used for reading elements sequentially.
- Output Iterator: Used for writing elements sequentially.
- Forward Iterator: Supports reading and writing; can move forward only.
- Bidirectional Iterator: Supports forward and backward traversal.
- Random Access Iterator: Allows access to any element in constant time.
Examples of Iterators
1. Input Iterator
Input iterators are used for sequential reading of elements.
Example:
#include <iostream> #include <vector> using namespace std; int main() { vectornumbers = {10, 20, 30, 40}; vector ::iterator it; for (it = numbers.begin(); it != numbers.end(); ++it) { cout << *it << " "; } return 0; }
2. Output Iterator
Output iterators are used for writing values to a container.
Example:
#include <iostream> #include <vector> #include <iterator> using namespace std; int main() { vectornumbers(5); fill(numbers.begin(), numbers.end(), 100); for (int num : numbers) { cout << num << " "; } return 0; }
3. Forward Iterator
Forward iterators allow reading and writing elements while moving forward.
Example:
#include <iostream> #include <list> using namespace std; int main() { listnumbers = {1, 2, 3, 4}; list ::iterator it; for (it = numbers.begin(); it != numbers.end(); ++it) { cout << *it << " "; } return 0; }
4. Bidirectional Iterator
Bidirectional iterators allow traversal in both forward and backward directions.
Example:
#include <iostream> #include <list> using namespace std; int main() { listnumbers = {10, 20, 30, 40}; list ::iterator it; // Forward traversal for (it = numbers.begin(); it != numbers.end(); ++it) { cout << *it << " "; } cout << endl; // Backward traversal for (it = --numbers.end(); it != --numbers.begin(); --it) { cout << *it << " "; } return 0; }
5. Random Access Iterator
Random access iterators allow direct access to elements in constant time using arithmetic operations.
Example:
#include <iostream> #include <vector> using namespace std; int main() { vectornumbers = {5, 10, 15, 20}; vector ::iterator it = numbers.begin(); cout << "First element: " << *it << endl; it += 2; cout << "Third element: " << *it << endl; return 0; }
Conclusion
Iterators are fundamental to working with STL containers in C++. Understanding the different types of iterators and their uses allows for efficient traversal and manipulation of container elements.