distance |
Calculate the span between two iterators.
Increment n by the number of steps it takes to traverse from first to last .
#include <algorithm>
template< class InputIterator, class Distance >
void distance
(
InputIterator first,
InputIterator last,
Distance& n
);
Time complexity is constant for random access iterators and linear for all other iterators. Space complexity is constant.
#include <iostream>
#include <iterator>
#include <vector>
void
main()
{
vector< int > v( 10 );
for ( int i = 0; i < v.size(); ++i )
v[ i ] = 100 + i;
// Find something in the middle.
vector< int >::iterator location = v.begin();
advance( location, 8 );
vector< int >::difference_type n = 0;
distance( v.begin(), location, n );
cout << n << "\n";
// Notice that n is incremented, not reset.
distance( location, v.end(), n );
cout << n << "\n";
distance( v.begin(), v.end(), n );
cout << n << "\n";
}
8
10
20
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.