std::distance

Header: <iterator>

Returns the number of hops from first to last.

# Declarations

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

(constexpr since C++17)

# Parameters

# Return value

The number of increments needed to go from first to last.

# Example

#include <iostream>
#include <iterator>
#include <vector>
 
int main() 
{
    std::vector<int> v{3, 1, 4};
    std::cout << "distance(first, last) = "
              << std::distance(v.begin(), v.end()) << '\n'
              << "distance(last, first) = "
              << std::distance(v.end(), v.begin()) << '\n';
              // the behavior is undefined (until LWG940)
 
    static constexpr auto il = {3, 1, 4};
    // Since C++17 `distance` can be used in constexpr context.
    static_assert(std::distance(il.begin(), il.end()) == 3);
    static_assert(std::distance(il.end(), il.begin()) == -3);
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 940C++98the wording was unclear for the case where first is reachable from lastmade clear

# See also