Iterator types
- C++ course
- Intermediate
- Lesson 61/116
- 5 min
Learn input, output, forward, bidirectional and random access iterators.
Iterator types
C++ defines five iterator categories. Each builds on the previous by adding abilities: input (read), output (write), forward (forward, multi-pass), bidirectional (also --) and random access (also + and []).
The container type sets the iterator category. std::vector and std::array give random access. std::list is bidirectional, std::forward_list is forward, and std::istream is an input iterator. The stronger the category, the more operations are supported.
Random access iterator
The random access iterator is the strongest category. It supports everything a pointer does: it + n for forward offset, it - n for backward offset, it2 - it1 for distance and it[n] to access the nth element.
std::vector, std::array and std::deque provide this category. Raw pointers are also random access iterators. That is why algorithms like std::sort require random access iterators and do not work on std::list.
Practice Access an element with random access
For v = {10, 20, 30, 40}, take an iterator with v.begin() and print the third element using it[2] with std::cout.
Starter code
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {10, 20, 30, 40};
// Take an iterator with begin(), access via index
return 0;
}Sample solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {10, 20, 30, 40};
auto it = v.begin();
std::cout << it[2];
return 0;
}Expected output
30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each container to its iterator category
| Term | Meaning |
|---|---|
std::vector |
Random access |
std::list |
Bidirectional |
std::forward_list |
Forward |
std::istream |
Input |
2 Access the third element
std::vector<int> v = {1, 2, 3};
auto it = v.begin();
std::cout << it[____];
std::vector<int> v = {1, 2, 3};
auto it = v.begin();
std::cout << it[2];
Explanation: it[2] reaches the third element (3).
3 Which container provides a bidirectional iterator?
// bidirectional iterator: --it supported- std::vector
- std::forward_list
- std::list Correct answer
- std::array
Explanation: std::list is bidirectional and supports --it.