Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::distance: counting steps between iterators

std::distance returns the number of increments needed to reach last from first, using subtraction for random-access iterators.

Version: C++23

Syntax

template<class InputIterator>
constexpr typename std::iterator_traits<InputIterator>::difference_type
distance(InputIterator first, InputIterator last);

std::distance(first, last) from <iterator> returns std::iterator_traits<InputIterator>::difference_type. For a random-access iterator the result is last - first in constant time; for other categories a copy of first is incremented until it reaches last, taking linear time.

last must be reachable from first. Random-access iterators also allow the reverse direction when first is reachable from last, in which case the result can be negative. The distance describes a number of steps; it does not imply that every iterator supports operator -.

An empty subrange yields zero. The iterators are passed by value, so the variable first itself is unchanged, but traversing a single-pass iterator, such as one tied to a stream, can consume the shared input resource. Do not use iterators from unrelated containers.

Examples

#include <iostream>
#include <iterator>
#include <list>

int main() {
    const std::list<int> values{10, 20, 30, 40};
    auto first = values.begin();
    ++first;
    std::cout << std::distance(first, values.end()) << '\n';
}

Result

3

std::distance → 3

Sources