Learning C++ part 4
Table of Contents
Iterators
Iterators provide a uniform abstraction for traversing elements in a container. Different iterator categories define what operations are supported, such as reading values, writing values, or moving forward and backward through a sequence. Each iterator category builds upon the capabilities of the previous one.
Input Iterators
Access: Read-only access to elements (*it behaves as an rvalue).
Traversal: Can only move forward using ++it.
Passes: Single-pass. Once incremented, the previous position cannot be reliably revisited.
Example: std::istream_iterator
Output Iterators
Access: Write-only access to elements (*it behaves as an lvalue).
Traversal: Can only move forward using ++it.
Passes: Single-pass. Values written cannot be read back through the iterator.
Example: std::ostream_iterator
Forward Iterators
Access: Support both reading and writing (*it can act as both rvalue and lvalue).
Traversal: Can move forward using ++it.
Passes: Multi-pass. Multiple copies of the iterator can traverse the same range independently.
Containers: Used by containers such as std::forward_list.
Bidirectional Iterators
Access: All capabilities of forward iterators (read/write, multi-pass).
Traversal: Can move forward ( ++it) and backward ( --it).
Containers: Used by containers such as std::list, std::set, and std::map.
Random Access Iterators
Access: All capabilities of bidirectional iterators.
Traversal: Support constant-time jumps using pointer arithmetic such as it + n, it - n, it += n, and it -= n.
Comparison: Support full ordering comparisons (<, >, <=, >=).
Containers: Used by containers like std::vector, std::deque, and std::array.
Note: Raw pointers are also considered random access iterators.
1#include <vector>
2#include <iostream>
3
4int main() {
5 std::vector<int> v = {1, 2, 3, 4};
6
7 for (auto it = v.begin(); it != v.end(); ++it) {
8 std::cout << *it << " ";
9 }
10}