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 | (until C++11) | |
If | (since C++11) |
first | - | iterator pointing to the first element |
last | - | iterator pointing to the end of the range |
Type requirements | ||
-InputIt must meet the requirements of InputIterator . The operation is more efficient if InputIt additionally meets the requirements of RandomAccessIterator |
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).
Linear.
However, if InputIt
additionally meets the requirements of RandomAccessIterator
, complexity is constant.
#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'; }
Output:
distance(first, last) = 3 distance(last, first) = -3
advances an iterator by given distance (function) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/iterator/distance