CodeBlanks Logo Icon CodeBlanks

What are iterators?

Learn what iterators are and their relation to containers.

What are iterators?

An iterator is a pointer-like object that gives access to elements in a container. Like pointers it is dereferenced with *, advanced to the next element with ++ and compared with !=.

Example: for std::vector<int> v = {10, 20, 30}; the call auto it = v.begin(); returns an iterator to the first element. *it reads the value 10. ++it moves to the next element. Iterators let you write one loop that works regardless of the container type.

Dereference and advance

An iterator has two core operations. *it reads or writes the element it points at. ++it moves it to the next element. These two form the loop body.

Example loop: auto it = v.begin(); while (it != v.end()) { std::cout << *it << " "; ++it; }. Here it != v.end() keeps the loop going while the iterator has not moved past the last element. *it prints the element each step and ++it advances to the next. This way every element of the container is printed in turn.

Practice Print a vector using an iterator

For the vector v = {10, 20, 30}, take an iterator with v.begin() and in a while loop print each element with *it. Add a space after each element.

Starter code

main.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {10, 20, 30};
    // Take an iterator and print with a while loop
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {10, 20, 30};
    auto it = v.begin();
    while (it != v.end()) {
        std::cout << *it << " ";
        ++it;
    }
    return 0;
}

Expected output

10 20 30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which operation is NOT valid on every iterator?

main.cpp
auto it = v.begin();
  • Take an offset with it + 2 Correct answer
  • Advance with ++it
  • Access the element with *it
  • Compare with it != v.end()

Explanation: it + 2 is valid only on random access iterators.

2 Print the element in the loop body

Question
auto it = v.begin();
while (it != v.end()) {
    std::cout << ____;
    ++it;
}
Answer
auto it = v.begin();
while (it != v.end()) {
    std::cout << *it;
    ++it;
}

Explanation: *it accesses the element the iterator points at.

3 Match each operation to its role

Term Meaning
auto it = v.begin() Iterator to first
*it Access element
++it Move to next
it != v.end() Loop condition

All lessons in Intermediate