std::ranges::distance

Header: <iterator>

1,2) Returns the number of hops from first to last.

# Declarations

Call signature
template< class I, std::sentinel_for<I> S >
requires (!std::sized_sentinel_for<S, I>)
constexpr std::iter_difference_t<I>
distance( I first, S last );

(since C++20)

template< class I, std::sized_sentinel_for<std::decay_t<I>> S >
constexpr std::iter_difference_t<std::decay_t<I>>
distance( I&& first, S last );

(since C++20)

template< ranges::range R >
constexpr ranges::range_difference_t<R>
distance( R&& r );

(since C++20)

# Parameters

# Example

#include <cassert>
#include <forward_list>
#include <iterator>
#include <vector>
 
int main() 
{
    std::vector<int> v{3, 1, 4};
    assert(std::ranges::distance(v.begin(), v.end()) == 3);
    assert(std::ranges::distance(v.end(), v.begin()) == -3);
    assert(std::ranges::distance(v) == 3);
 
    std::forward_list<int> l{2, 7, 1};
    // auto size = std::ranges::size(l); // error: not a sizable range
    auto size = std::ranges::distance(l); // OK, but aware O(N) complexity
    assert(size == 3);
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 3392C++20overload (1) takes iterator by value, thus move-onlyiterator lvalue with a sized sentinel was rejectedadded overload (2)
LWG 3664C++20the resolution of LWG issue 3392 maderanges::distance reject array argumentsaccepts them

# See also