Library: Iterators
Function
A function that computes the distance between two iterators
#include <iterator> namespace std { template <class ForwardIterator> iterator_traits<ForwardIterator>::difference_type distance(ForwardIterator start, ForwardIterator finish); template <class ForwardIterator, class Distance> void distance(ForwardIterator start, ForwardIterator finish, Distance& n); }
The distance() function template computes the distance between two iterators. The first version returns that value, while the second version increments n by that value. The last iterator must be reachable from the first iterator.
Note that the second version of this function is obsolete. It is included for backward compatibility and to accommodate compilers that do not support partial specialization. The first version of the function is not available with compilers that do not support partial specialization, since it depends on iterator_traits, which itself depends on that particular language feature.
// // distance.cpp // #include <iterator> #include <iostream> #include <vector> int main () { // Typedefs for convenience. typedef std::vector<int, std::allocator<int> > vector; typedef std::ostream_iterator<vector::value_type, char, std::char_traits<char> > os_iter; // Initialize a vector using an array. const vector::value_type arr [] = { 3, 4, 5, 6, 7, 8 }; const vector v (arr + 0, arr + sizeof arr/ sizeof *arr); // Declare a vector iterator, s.b. a ForwardIterator. vector::const_iterator it = v.begin () + 3; // Output the original vector. std::cout << "For the vector: "; std::copy (v.begin (), v.end (), os_iter (std::cout, " ")); std::cout << std::endl; std::cout << "\nWhen the iterator is initialized " << "to point to " << *it << std::endl; // Compute the distance of it from the first element. vector::difference_type dist = 0; std::distance (v.begin (), it, dist); std::cout << "The distance between the beginning and " << *it << " is " << dist << std::endl; return 0; } Program Output:
For the vector: 3 4 5 6 7 8 When the iterator is initialized to point to 6 The distance between the beginning and 6 is 3
If your compiler does not support partial specialization, you can't use the version of distance() that returns the distance. Instead, you must use the version that increments a reference parameter.
Sequences, Random Access Iterators
ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 24.3.4