CodeBlanks Logo Icon CodeBlanks

Iterator arithmetic

Learn arithmetic on random access iterators.

Iterator arithmetic

Random access iterators support pointer arithmetic. it + n gives the position n elements forward, it - n gives n elements back. it2 - it1 gives the distance between two iterators as a count of elements. it[n] is shorthand for *(it + n).

These operations work only on random access iterators. Using + on a forward or bidirectional iterator causes a compile error. Containers like std::vector and std::array support this arithmetic; std::list does not.

std::distance

There are two ways to find the distance between two iterators. On random access iterators it2 - it1 gives the distance directly. For other categories use std::distance(it1, it2), which advances step by step.

To find the index of an element use std::distance(v.begin(), it). For example after auto it = std::find(v.begin(), v.end(), 30); the call std::distance(v.begin(), it) gives the index of 30. This is the standard way to convert an iterator to an index.

Practice Access the third element via offset

For v = {7, 14, 21, 28}, take an iterator with v.begin() and print the third element using *(it + 2) with std::cout.

Starter code

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

int main() {
    std::vector<int> v = {7, 14, 21, 28};
    // Take an iterator with begin(), access via offset
    return 0;
}

Sample solution

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

int main() {
    std::vector<int> v = {7, 14, 21, 28};
    auto it = v.begin();
    std::cout << *(it + 2);
    return 0;
}

Expected output

21

Questions and answers

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

1 Match each operation to its result

Term Meaning
it + 3 Forward offset
it - 2 Backward offset
it2 - it1 Distance
it[n] nth element

2 Which operation works only on random access iterators?

main.cpp
// this operation does not work on every iterator
  • Take offset with it + 5 Correct answer
  • Dereference with *it
  • Advance with ++it
  • Compare with it != end

Explanation: it + 5 works only on random access iterators.

3 Compute the index

Question
auto idx = std::____(v.begin(), it);
Answer
auto idx = std::distance(v.begin(), it);

Explanation: std::distance converts an iterator to an index.

All lessons in Intermediate