Namespaces
Variants
Views
Actions

std::distance

From cppreference.com
< cpp‎ | iterator
 
 
Iterator library
Iterator concepts
Iterator primitives
Iterator adaptors
Stream iterators
Iterator customization points
Iterator operations
distance
(C++11)
(C++11)
Range access
(C++11)(C++14)
(C++11)(C++14)
(C++17)(C++20)
(C++14)(C++14)
(C++14)(C++14)
(C++17)
(C++17)
 
Defined in header <iterator>
template< class InputIt >

typename std::iterator_traits<InputIt>::difference_type

    distance( InputIt first, InputIt last );
(until C++17)
template< class InputIt >

constexpr typename std::iterator_traits<InputIt>::difference_type

    distance( InputIt first, InputIt last );
(since C++17)

Returns the number of hops from first to last.

The behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first.

(until C++11)

If InputIt is not LegacyRandomAccessIterator, the behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first. If InputIt is LegacyRandomAccessIterator, the behavior is undefined if last is not reachable from first and first is not reachable from last.

(since C++11)

Contents

[edit] Parameters

first - iterator pointing to the first element
last - iterator pointing to the end of the range
Type requirements
-
InputIt must meet the requirements of LegacyInputIterator. The operation is more efficient if InputIt additionally meets the requirements of LegacyRandomAccessIterator

[edit] Return value

The number of increments needed to go from first to last. The value may be negative if random-access iterators are used and first is reachable from last (since C++11)

[edit] Complexity

Linear.

However, if InputIt additionally meets the requirements of LegacyRandomAccessIterator, complexity is constant.

[edit] 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 C++11)
}

Output:

distance(first, last) = 3
distance(last, first) = -3

[edit] See also

advances an iterator by given distance
(function template) [edit]
returns the number of elements satisfying specific criteria
(function template) [edit]