Iterators
Iterator types and usage
Interview Relevant: STL navigation
Iterators
Generalized pointers for traversing containers.
Code Examples
Iterator categories and operations.
cpp
1vector<int> v = {1, 2, 3, 4, 5};
2
3// Iterator types
4vector<int>::iterator it = v.begin();
5vector<int>::const_iterator cit = v.cbegin();
6vector<int>::reverse_iterator rit = v.rbegin();
7
8// Iterator operations
9*it; // Dereference
10++it; // Advance
11--it; // Move back
12it += 3; // Random access (vector/deque only)
13it2 - it1; // Distance
14
15// Iterator categories:
16// - Input: read once, forward only
17// - Output: write once, forward only
18// - Forward: read/write, forward only
19// - Bidirectional: forward and backward
20// - Random Access: any position in O(1)
21
22// begin/end variations
23v.begin(); v.end(); // Regular
24v.cbegin(); v.cend(); // Const
25v.rbegin(); v.rend(); // Reverse
26v.crbegin(); v.crend(); // Const reverse
27
28// Insert iterators
29vector<int> dest;
30copy(v.begin(), v.end(), back_inserter(dest));
31
32// Stream iterators
33copy(v.begin(), v.end(),
34 ostream_iterator<int>(cout, " "));