Home | Projects | Notes > C++ Programming > Introduction to STL Iterators
Iterators allow you to abstract any container as a sequence of elements, without needing to know how the container is implemented under the hood.
They are implemented as template classes and behave like pointers by design—you can use operators like *
(dereference), ++
/--
(increment/decrement), etc.
Most container classes support traversal using iterators.
Exceptions include container adapters such as std::stack
and std::queue
, which do not provide iterator access.
Iterators must be declared based on the container type they will iterate over.
11container_type::iterator_type iterator_name;
41std::vector<int>::iterator it1; // Can only be used to iterate over 'vector<int>'
2std::list<std::string>iterator it2;
3std::map<std::string, std::string>::iterator it3;
4std::set<char>::iterator it4;
begin()
and end()
MethodsNote that the end()
does not point to the last element but the one PAST the last element and is not dereferenceable. (Accessing *end()
is undefined behavior.)
To initialize iterators:
21std::vector<int> v {1, 2, 3};
2std::vector<int>::itrator it = v.begin();
or let the compiler deduce the type by using auto
keyword:
11auto it = v.begin();
More readable, writable and easier to debug.
If the vector is empty, v.begin()
will return v.end()
.
The following table sumarizes the most commonly used iterator operations.
It is assumed that it
is an iterator, and i
is an integer.
Function | Description | Type of Iterator |
---|---|---|
++it | Pre-increment | All |
it++ | Post-increment | All |
it = it1 | Assignment (LHS and RHS types must be the same) | All |
*it | Dereference | Input and output |
it-> | Arrow operator | Input and output |
it == it1 | Comparison for equality | Input |
it != it1 | Comparison for inequality | Input |
--it | Pre-decrement | Bidirectional |
it-- | Post-decrement | Bidirectional |
it + i , it += i it - i , it -= i | Increment and decrement | Random access |
it < it1 , it <= it1 it > it1 , it >= it1 | Comparison | Random access |
Using iterators - std::vector
71std::vector<int> v {1, 2, 3};
2std::vector<int>::iterator it = v.begin();
3while (it != v.end())
4{
5 std::cout << *it << " ";
6 ++it;
7}
111 2 3
Can also use for
loop instead of while
loop:
41for (auto it = v.begin(); it != b.end(); it++)
2{
3 std::cout << *it << " ";
4}
This is how the range-based
for
loop works.
Using iterators - std::set
61std::set<char> s {'C', 'H', 'S', 'D'};
2auto it = s.begin();
3while (it != s.end())
4{
5 std::cout << *it << " " << std::endl;
6}
11C H S D
The same pattern as with the
std::vector
.
Reverse iterators works in reverse direction. The last element is the first and the first is the last. (++
moves backward, --
moves forward.)
71std::vector<int> v {1, 2, 3};
2std::vector<int>::reverse_iterator rit = v.begin(); // Points to the last element
3while (rit != v.end())
4{
5 std::cout << *it << " ";
6 ++it; // Here ++ moves backward
7}
113 2 1
begin()
and end()
- iterator
cbegin()
and cend()
- const_iterator
rbegin()
and rend()
- reverse_iterator
crbegin()
and crend()
- const_reverse_iterator
x
1
2
3
4
5
6
7// Display any vector of integers using range-based for loop
8void print(const std::vector<int> &v)
9{
10 std::cout << "[ ";
11 for (auto const &n : v)
12 {
13 std::cout << n << " ";
14 }
15 std::cout << "]" << std::endl;
16}
17
18void test1(void)
19{
20 std::cout << "\nTEST1" << std::endl;
21
22 std::vector<int> v{1, 2, 3, 4, 5};
23 auto it = v.begin(); // Points to 1
24 std::cout << *it << std::endl;
25
26 it++; // Points to 2
27 std::cout << *it << std::endl;
28
29 it += 2; // Points to 4
30 std::cout << *it << std::endl;
31
32 it -= 2; // Points to 2
33 std::cout << *it << std::endl;
34
35 it = v.end() - 1; // Points to 5
36 std::cout << *it << std::endl;
37
38}
39
40// Display all vector elements using an iterator.
41void test2(void)
42{
43 std::cout << "\nTEST2" << std::endl;
44
45 std::vector<int> v{1, 2, 3, 4, 5};
46
47 std::vector<int>::iterator it = v.begin();
48
49 while (it != v.end())
50 {
51 std::cout << *it << std::endl;
52 it++;
53 }
54
55 // Change all vector elements to 0.
56 it = v.begin();
57 while (it != v.end())
58 {
59 *it = 0;
60 it++;
61 }
62
63 print(v);
64}
65
66// Using a const iterator.
67void test3(void)
68{
69 std::cout << "\nTEST3" << std::endl;
70
71 std::vector<int> v{1, 2, 3, 4, 5};
72 std::vector<int>::const_iterator cit = v.begin();
73 // auto cit = v.cbegin();
74
75 while (cit != v.end())
76 {
77 std::cout << *cit << std::endl;
78 cit++;
79 }
80
81 // Compiler error upon an attempt to change elements
82 cit = v.begin();
83 while (cit != v.end())
84 {
85 // *cit = 0; // Compiler error - read only!
86 cit++;
87 }
88}
89
90// More iterators.
91void test4(void)
92{
93 // Using a reverse iterator over a vector.
94 std::vector<int> v{1, 2, 3, 4};
95 auto rit = v.rbegin(); // Starts at 4.
96 while (rit != v.rend())
97 {
98 std::cout << *rit << std::endl;
99 rit++;
100 }
101
102 // Const reverse iterator over a list (implemented as doubly-linked list).
103 std::list<std::string> l{"Kyungjae", "Sunny", "Yena"};
104 auto crit = l.crbegin(); // Points to Yena.
105 std::cout << *crit << std::endl;
106 crit++; // Points to Sunny.
107 std::cout << *crit << std::endl;
108
109 // Iterator over a map.
110 std::map<std::string, std::string> m{
111 {"Kyungjae", "C++"},
112 {"Sunny", "Python"},
113 {"Yena", "Assembly"}
114 };
115 auto it = m.begin(); // Iterator over map of <string, string> pairs.
116 while (it != m.end())
117 {
118 std::cout << it->first << ":" << it->second << std::endl;
119 it++;
120 }
121}
122
123// Iterator over a subset of a container
124void test5(void)
125{
126 std::cout << "\nTEST5" << std::endl;
127
128 std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
129 auto s = v.begin() + 2; // Start
130 auto e = v.end() - 3; // End
131 while (s != e)
132 {
133 std::cout << *s << std::endl;
134 s++;
135 }
136}
137
138int main(int argc, char *argv[])
139{
140 test1();
141 test3();
142 test3();
143 test4();
144 test5();
145 return 0;
146}
1371
2TEST1
31
42
54
62
75
8
9TEST3
101
112
123
134
145
15
16TEST3
171
182
193
204
215
224
233
242
251
26Yena
27Sunny
28Kyungjae:C++
29Sunny:Python
30Yena:Assembly
31
32TEST5
333
344
355
366
377